Software QA FYI - SQAFYI

PHP Unit Testing with PHPUnit

By: Kendrick Curtis

Unit testing is the process of testing discrete code objects – such as functions, classes or methods – by using either bespoke testing code or by utilizing a pre-existing testing framework such as JUnit, PHPUnit or Cantata++. Unit testing frameworks provide a host of common, useful functionality for writing automated unit tests such as assertions to check whether a certain value was as expected and often include reports of line and decision coverage to tell you how much of your codebase you have.

PHPUnit is available as a PEAR package, a Composer bundle or as a PHAR file. However you install it, you must also install the PHP Code Coverage dependency first. In PEAR, you need to add the channel and then install the two packages from the command line:

PHP Unit Testing with PHPUnit

(Note that at the time of writing, the default PEAR installation with XAMPP is broken: you’ll need to get the PEAR PHAR and install that from the command line before attempting the above).

Testing A Simple Class
Consider an extremely simple PHP class with a single method:
class TruthTeller
public function() tellTruth
return true;

Sure, tellTruth always returns true now, but how can we check that with a unit test to ensure that it always returns this result in the future?

With PHPUnit, every set of tests is a class extended from the PHPUnit_Framework_TestCase class, which provides common useful functionality such as assertions. Here’s a basic test for the tellTruth method above:

require_once 'PHPUnit/Autoload.php';
require_once 'TruthTeller.class.php';
class TruthTester extends PHPUnit_Framework_TestCase
function testTruthTeller()
$tt = new TruthTeller();

Note that you need to include both the PHPUnit autoloader and also the “object under test”, in this case, the TruthTeller class file.

All we are doing with the rest of the code is asserting that if the tellTruth method is called, it will return true. These assertions are the core of PHPUnit – they are what will determine whether a test passes or fails.

If you were to fire up a command prompt, switch to the directory with your tests in and run phpunit TruthTester (the parameter is the file name of your tests file, minus the .php extension), PHPUnit will run all of the tests it can find in the file specified (a test being any method that begins with the word “test”).

Full article...

Other Resource

... to read more articles, visit

PHP Unit Testing with PHPUnit