Here, we will learn how to write the tests using the PHPUnit. First of all, we have to download the composer installer in our root folder using the command:
curl -s http://getcomposer.org/installer | php
Then, we have to create a composer.json file in the root and put the following lines into it:
{ "require": { "phpunit/phpunit": "4.0.*" } }
Here, I used version 4.0.* instead of 5.0.* because version 5 requires PHP version 5.6 but I could only afford version 5.5.9.
After pasting the above lines, we have to install the dependencies using the command:
php composer.phar install
It will create a vendor folder by default in which the PHPUnit packages will be stored.
Now, create a folder in which all the code files will be placed and a folder named Test need to be created parallel to those files in which all the files containing tests will be placed.
The file name and the class name of the tests should be same. The class name must end with ‘Test’ and function name must start with ‘test’. So, the class name will look like ‘class_nameTest’ and function name will look like ‘testfunction_name’.
So, here I have created a file name OneTest.php in the Test folder and the code placed in this file is as follows:
<?php namespace phpUnitTutorial\Test; class OneTest extends \PHPUnit_Framework_TestCase { public function testTrue() { $foo = true; $this->assertTrue($foo); } /** * @test */ public function failure() { $foo1 = array(1, 2, 3, 4, 5, 6); $foo2 = array('1', 2, 33, 4, 5, 6); // taken from the php unit docs $this->assertEquals($foo1,$foo2); } }
You can also write @test in php docs so that it will recognize it as test function even if it don’t have the prefix ‘test’ like I did in second function.
After writing tests, you have to create a XML file named phpunit.xml in the root folder which represents the path of the test files. Here, I have created a file named phpunit.xml as:
<?xml version="1.0" encoding="UTF-8"?> <phpunit colors="true"> <testsuites> <testsuite name="Application Test Suite"> <directory>./phpUnitTutorial/Test/</directory> </testsuite> </testsuites> </phpunit>
Now after doing so, you have to run test in the Terminal as:
vendor/bin/phpunit
Here are a few outputs of tests performed:
When no test class was found
While making tests over the first function in the test file
While making tests over both the functions in the test file
For a thorough knowledge of the PHPUnit, please do visit PHPUnit Documentation.
Be the first to comment.