How to unit test with phpunit¶
PHPUnit is the industry-standard framework for unit testing PHP code. All PHP projects should use this package, and MRs which contribute new code should come with unit tests.
Install PHPUnit¶
First you'll need to install composer
Next, install PHPUnit with composer:
composer require phpunit/phpunit --dev
Notice that the --dev
switch installs the package for development environments, not deployment environments.
Now you should have the latest version of PHPUnit:
$ ./vendor/bin/phpunit --version
PHPUnit 6.5.13 by Sebastian Bergmann and contributors.
Creating a new test¶
From the root directory of your web application, use artisan
to create a new test:
php artisan make:test NameOfTest
The new test will be inside tests/Feature
.
Conventions¶
$this
has its usual meaning.factory
A factory of is used to create new classes or objects.post
performs an HTTP post.get
performs an HTTP get.put
performs an HTTP put.delete
performs an HTTP delete.assertStatus
Checks the HTTP status code in the test.assertSee
Checks what you "see" in the test.
Example login test¶
public function testSuccessfulLogin()
{
$user = factory(\App\User::class)->create([
'username' => 'Testing',
'email' => 'testing@testing.com',
'password' => bcrypt('testpass123')
]);
$response = $this->followingRedirects()
->post('/login', ['email' => 'testing@testing.com', 'password' => 'testpass123'])
->assertStatus(200)
->assertSee($user->username);
}
A successful test will look like this:
$ ./vendor/bin/phpunit
PHPUnit 6.5.13 by Sebastian Bergmann and contributors.
............................................................... 63 / 107 ( 58%)
............................................ 107 / 107 (100%)
Time: 24.65 seconds, Memory: 34.00MB
OK (107 tests, 443 assertions)