Saturday, February 16, 2019

How to use phpunit in Laravel 5.7

Table of contents
1. how to start
2. create a basic user creation page
3. create unit tests for Laravel 5.7

How to use phpunit in Laravel 5.7

We can use phpunit and phpspec by default in Laravel 5.7. The test files have to be saved in /vagrant/laravel/tests/Unit/vagrant/laravel/tests/Feature (or /vagrant/laravel/tests/Browser if you use dusk). Also you can simply use the artisan command to create unit tests:
$ cd /vagrant/laravel
# Test file will be saved in laravel/tests/Feature directory
$ php artisan make:test UserTest
# Test file will be saved in laravel/tests/Unit directory
$ php artisan make:test UserTest --unit
You can see the generated file in /vagrant/laravel/tests/Feature or in /vagrant/laravel/tests/Unit. The code in the file is like this:
namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);
    }
}
You can see that the UserTest class is extending TestCase class. When you write unit tests by yourself, you need to extend TestCase class. Or just run the artisan make:test command and customize the generated file.

Run Unit tests

To run the unit tests, use this command:
$ cd /vagrant/laravel
# Run all unit tests
$ vendor/bin/phpunit
# Run only unit tests in Unit directory
$ vendor/bin/phpunit tests/Unit
# Run only unit tests in Feature directory
$ vendor/bin/phpunit tests/Feature

Create Unit tests

We learned how to create base unit test files. In this section, we will see examples of unit tests. You can see various examples in the official laravel documentation; HTTP TestsConsole TestsBrowser TestsDatabase TestingMocking. So please check the website for the detailed information.
This is one of the examples. To check if a page returns 200:
<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

Unit test to check if user is successfully created

Dusk
If you have followed these posts: Set up LaravelCreate a basic user creation page, you should have a /submit page to create a user. I wrote a unit test for the page.
For the browser test, you need to install dusk at first.
$ cd /vagrant/laravel
$ composer require --dev laravel/dusk
$ php artisan dusk:install
$ composer dump-autoload
We need to install the chrome binary in CentOS 7.
$ vi /etc/yum.repos.d/google.chrome.repo
Write inside the file this and save it:
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
Install the chrome binary:
$ sudo yum update
$ sudo yum install google-chrome-stable
By default, Dusk uses Google Chrome and a standalone ChromeDriver installation to run your browser tests. To use other browser, see this explanation.
To make a base unit test:
$ php artisan dusk:make LoginTest
You can find the file in /vagrant/laravel/tests/browser.
<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class LoginTest extends DuskTestCase
{
    /**
     * A Dusk test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSee('Laravel');
        });
    }
}
Change it like this. This is the test to check if users can be created.
<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class LoginTest extends DuskTestCase
{
    /**
     * A Dusk test example.
     *
     * @return void
     */
    public function testUserCreation()
    {
        $this->browse(function (Browser $browser) {
            $datetime = date('Y_d_m_h_i_s_a', time());
            $browser->visit('/submit')
                ->type('name', 'test_'.$datetime)
                ->type('email', 'test'.$datetime.'@test.com')
                ->type('password', 'password_'.$datetime)
                ->click('#submitBtn')
                ->assertPathIs('/');
        });
    }
}
You can run the browser test by the following command:
$ cd /vagrant/laravel
$ php artisan dusk
The test result is:

References