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.
class PostTest extends TestCase
* @return void
public function testExample()
->see('result for "query"')
then run phpunit command on Terminal and hit enter
Again , it should fail at first time.
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.
<form action="/search-result" method="post">
<input id="search" type="text" name="search"/>
<button type="submit" name="Go">Go</button>
in \app\http\routes.php , that because
We should see string ‘result for “query”’ in the page URL ‘/search-result’
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.