
I have been using PHPUnit for quite some time now. I thought a few times about writing about it, but it hasn’t happened till now. This is my first tutorial on testing as well. The official documentation/getting started guide is already quite good. However, I find it a little insufficient in several cases and could be a little hard to start with as a beginner. Thus, I am writing this PHPUnit tutorial to explain it as easily as possible, using my preferred/recommended way to begin using PHPUnit. Also, though this is a beginner’s level tutorial on PHPUnit, I assume you know/have a sound concept of unit testing!
Alternative To PHPUnit:
There is another simpletest for PHP, which you can check out as well if you want. However, though I haven’t practically used it yet, it seems it doesn’t have as much support/flexibility as PHPUnit. Also, even PHPUnit is unofficial. Still, it’s almost being used everywhere, so sticking with it is a good idea, I guess.
Installing PHPUnit:
It is possible to get PHPUnit installed on a per-project basis or system-wide as well. I personally prefer a per-project basis most. Let’s install this way using composer:
{
"require": {
"phpunit/phpunit": "dev-master"
}
}
Code language: JSON / JSON with Comments (json)
Even if you are not using Composer for your project, you can have it there without affecting anything else and comfortably use its CLI. In case you are not familiar with Composer, get it installed easily on your system, copy the above JSON to a file named ‘composer.json’ in your project directory, and run the ‘composer update’ command. And that should be it.
Now, to verify the installation, use your terminal/command line tool and go to your project directory. Then run the following command:
$./vendor/bin/phpunit
PHPUnit 4.1.3 by Sebastian Bergmann.
Usage: phpunit [options] UnitTest [UnitTest.php]
phpunit [options] <directory>
Code Coverage Options:
..............
Code language: HTML, XML (xml)
If all is OK, you should get some output like the above.
Initial PHPUnit Configuration:
Well, it’s not mandatory to maintain a configuration file. You can run a specific PHPUnit class/method right from your CLI. However, I like, prefer, and strongly recommend having a configuration file with all the details so that you can just run the “phpunit” command, and it will take care of the rest.
Yes, if there is a configuration file named ‘phpunit.xml’, the library automatically reads it and acts accordingly. A sample configuration file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./tests/bootstrap.php"
convertWarningsToExceptions="true"
convertNoticesToExceptions="true"
convertErrorsToExceptions="true"
backupStaticAttributes="false"
processIsolation="false"
stopOnFailure="false"
backupGlobals="false"
syntaxCheck="false"
colors="true">
<testsuites>
<testsuite name="HelloWorld Test Suite">
<directory>./tests/</directory>
<file>./path/to/file.php</file>
</testsuite>
</testsuites>
<php>
<var name="SOME_CONSTANT_CONFIG" value="Test Value" />
</php>
</phpunit>
Code language: HTML, XML (xml)
Above is a straightforward XML configuration. As you can see, you can specify directories where your test files are. You can select individual files as well. Also, you can categorize tests into separate test suits here. Then, you can just run one specific suit from CLI.
PHPUnit HelloWorld Test Case:
Let’s create a test to try out. It’s good to have tests on a separate dedicated directory, usually named ‘tests’. Create a single PHP file named ‘HelloWorldTest’ and put the below content in it:
class HelloWorldTest extends PHPUnit_Framework_TestCase
{
function testHelloWorld()
{
$this->assertTrue(true);
}
}
Code language: PHP (php)
Just to tell you one thing here, remember that a PHPUnit test method name always starts with ‘test’, and the rest of the name goes one. PHPUnit will ignore any method that doesn’t start with ‘test’.
For this first test, remove the bootstrap option from the XML configuration(as we don’t have any now). Run the following command:
$./vendor/bin/phpunit
Code language: JavaScript (javascript)
If all are OK, you should see something like as below:
PHPUnit 4.3-g39989b7 by Sebastian Bergmann.
Configuration read from /path/to/phpunit.xml
.
Time: 793 ms, Memory: 2.50Mb
OK (1 test, 1 assertion)
Code language: JavaScript (javascript)
As you can see, in summary, the output shows the most necessary information, in brief, like how many tests(each test method is considered a single test; However, a single test can include as many assertions as you need) ran, how much time/memory it took, etc.
Understanding Assertion:
The assertion is the process of verifying an expected output to actual output. This is something like this – you will provide a set of input(s) to a unit of functionality(usually a specific method) in your application. Then, you verify whether your desired output is the same as the actual output the method returns to you. If yes, it passes the test; otherwise, it fails.
There are several built-in assert* methods(which are standards on unit tests of other programming languages as well) that you will use to compare the value your application is returning to the value you are expecting. Let’s say your application has a class that checks whether a user is logged in or not. This could be written in PHPUnit as below:
function testAuthorized()
{
$this->assertTrue(Auth::isLoggedIn());
}
Code language: PHP (php)
In a similar way, you can compare two values as well:
function testPHPUnitMethod()
{
$company = CompanyModel::getByName("companyName");
$this->assertEqual(50, $company->noOfEmployee());
}
Code language: PHP (php)
There are lots of other assertions available that you can use to compare almost anything you might need.
Initialization/Destruction:
Well, it might happen that you have several test cases that need to do several common steps at the beginning. To make a common generalization of such situations, PHPUnit comes up with built-in support for ‘setUp’ and ‘tearDown’ methods, which you can write
To do standard initialization and destruction mechanisms. The example is shown below:
public function setUp()
{
$this->db->ClearDatabase();
$this->session->start();
}
public function tearDown()
{
$this->session->destroy();
}
Code language: PHP (php)
Final Words:
As a starting point, I guess this small PHPUnit tutorial should be enough. However, if you are not clear about anything or if you think some other information will be helpful to add, please let me know via comment, and I will try to add them soon. Also, I am willing to write more on this later on. Happy coding 🙂
Discover more from CODESAMPLEZ.COM
Subscribe to get the latest posts sent to your email.
Without class ,How to test PHP functions?
I have following simple code inside my Index.php file
So how to test only message() functin without class by using PHPUnit inside NetBeans Framework.
This will help you
http://stackoverflow.com/questions/36016250/is-it-possible-to-unit-test-php-files-other-than-class-file-using-phpunit/36016329#36016329
$this->assertEqual(50, $company->noOfEmployee());
this should be ‘assertEquals’
but further than that, everything worked thanks!
Nice guide but I think you forgot to mention that before starting the test process, a proper directory structure for the files to be tested is required (mentioned here: https://www.cloudways.com/blog/getting-started-with-unit-testing-php/ ). This way you can efficiently run the test of your code.