phpunit testing:
- https://www.youtube.com/watch?v=-9YVcssCACI&t=244s
- Installation:
- composer require –dev phpunit/phpunit
- Usage on cli:
- If it’s installed with composer in your project folder:
- go to your project folder
- .\vendor\bin\phpunit phptest.php
- go to your project folder
- If it’s installed with composer in your project folder:
- phpunit config file:
- create phpunit.xml
- specify the testsuite (filename, location etc)
- from the cli just use .\vendor\bin\phpunit
- file content
- Can use gruntjs for running phpunit
- Accessing Main Class from Test Class
- Autoload the main class location in composer.json
- “autoload”:{
“psr-4”:{
“App\\”:”app”
}
} - where ‘app’ is the folder location of the main class
- PSR 4 app loading:
- after specifying autoload execute following composer command to work with autoloaded classes
- composer dump-autoload -o
- “autoload”:{
- Using the main class in Test class
- create object $obj= new \App\ClassName; (fresh model for each method)
- User the $obj to access the class properties
- Naming for test methods:
- ‘test’ has to be pre-fixed for all test class methods and has camel case methods
- dot block method:
- /** @test */
- inserting this dot block before a method which has no ‘test’ pre-fix will run the test like other test cases which has ‘test’ pref-fix
- Using setUp as a constructor method for creating a model with a protected variable
- setUp runs before each method
- protected $user;public function setUp(){
$this->user = new \App\Models\User;
}
- Collection class
- convenient wrapper for any kind of objects
- for iterating purposes
- Important concepts:
- Assertions:
- assertTrue
- assertEquals
- assertEmpty
- assertInstanceOf
- assertCount
- assertInternalType
- Exceptions:
- expectExceptions
- Autoload the main class location in composer.json
Reference:
https://github.com/sainag/PHPUnit
https://phpunit.de/manual/current/en/organizing-tests.html
Tutorial series