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¶
$thishas its usual meaning.factoryA factory of is used to create new classes or objects.postperforms an HTTP post.getperforms an HTTP get.putperforms an HTTP put.deleteperforms an HTTP delete.assertStatusChecks the HTTP status code in the test.assertSeeChecks 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)