PHP Laravel : My First Unit testing using PHPUnit

Laravel 5 is a popular PHP framework. It relies on MVC pattern which is easy to work on. It also has TestCase class which stands for testing and has PHPUnit which is a test runner in project.

The PHPUnit always comes with project when we create new project. If there is not included in project, you can install it via Composer (follow this instruction ).

Typically , the way we test relies on A: Arrange , A: Act and A: Assertion. At first time we pretend to run the test to fail (It should fail first , because there is no any implementation. The purpose is ‘To remind myself what tasks need complete and pass the test’) , then we refactor code. Finally , we run test again. The final step must have ‘Green’ that means you pass the test. if it shows red , go back to loop and refactor the code.

Ok Let’s test (In very basic)

Change directory to you project file and run command line on Terminal

php artisan make:test PostTest

The test file named PostTest.php will be created. It is in \tests directory.

The PostTest , which extends from TestCase, give a testing method testExample by default. If you want to test another scenario , you have to create new test method.

In testExample , here is our scenario (Requirement) ,

When we visit URL ‘/’ we should see string ‘Create’ anywhere on page. When we type something like ‘query’ in form named ‘search’ and press ‘Go’ button to submit the form. We should see string ‘result for “query”’ in the page URL ‘/search-result’

here is our code in \tests\PostTest.php.

<?php

use
Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;



class PostTest extends TestCase
{
/**
*
@return void
*/
public function testExample()
{
$this->visit('/')
->see('Create')
->type('query', 'search')
->press('Go')
->see('result for "query"')
->seePageIs('/search-result');
}
}

then run phpunit command on Terminal and hit enter

phpunit

Again , it should fail at first time.

Refactor

in \resources\views\welcome.blade.php

When we visit URL ‘/’ we should see string ‘Create’ anywhere on page. When we type something like ‘query’ in form named ‘search’ and press ‘Go’ button to submit the form.
<h4>Create</h4>
<form action="/search-result" method="post">
<input id="search" type="text" name="search"/>
<button type="submit" name="Go">Go</button>
</form>

in \app\http\routes.php , that because

We should see string ‘result for “query”’ in the page URL ‘/search-result’
Route::post('/search-result',function(){
return 'result for "query"';
});

Wooohhh. we finish refactoring.

Then run PHPUnit runner again, It should OK in finally.

Here is the very basic unit testing in Laravel by using PHPunit, for more testing detail in Laravel visit here.

Show your support

Clapping shows how much you appreciated Chutipong Roobklom’s story.