Unit testing is an essential process in developing large projects. Unit tests help to automate the testing of the application’s components at every stage of development. It alerts when the component of the application is not working according to the business specification of the project. Unit testing can be done manually but is often automated.
FuelPHP framework integrates with the PHPUnit testing framework. To write a unit test for the FuelPHP framework, we need to set up the PHPUnit. If PHPUnit is not installed, then download and install it. We can confirm the availability of PHPUnit in our system using the following command.
phpunit --version
If PHPUnit is available, you will see the result similar to the following.
PHPUnit 5.1.3 by Sebastian Bergmann and contributors.
The standard location provided by FuelPHP to write unit test is fuel/app/tests. We can write the unit test for controller, model, view and presenters in separate folders. Let us write a unit test to validate the Model_Employee object.
Step 1 − Create a folder, model under fuel/app/tests folder.
Step 2 − Create a file, employee.php under fuel/app/tests/model/ folder.
Step 3 − Create a new test class, Test_Model_Employee by extending TestCase class provided of PHPUnit.
Step 4 − Write a method, testInstanceOfEmployee() to asset the employee object creation using assertInstanceOf() method provided by PHPUnit's TestCase class.
Following is the complete code −
<?php class Test_Model_Employee extends TestCase { public function testInstanceOfEmployee() { $this->assertInstanceOf(Model_Employee::class, new Model_Employee()); } }
FuelPHP provides an option to create a group of test cases. Creating a group is as simple as adding docblock attribute, @group. Let us include our test case inside the MyTest group.
<?php /** * @group MyTest */ class Test_Model_Employee extends TestCase { public function testInstanceOfEmployee() { $this->assertInstanceOf(Model_Employee::class, new Model_Employee()); } }
To run all the test in the directory, use the following command.
$ php oil test
To run a specific group of tests, use the following command.
$ php oil test --group = MyTest
After executing the command, you will receive the following response.
Tests Running...This may take a few moments. PHPUnit 5.1.3 by Sebastian Bergmann and contributors. 1 / 1 (100%). Time: 123 ms, Memory: 8.00Mb OK (1 test, 1 assertion)