Unit testing in programming is a well-known concept and PHPUnit has been around since 2004. Still, unit testing adoption in PHP business environments is poor. The obvious reason is that it requires a lot of additional code writing (4 lines of test code for each line of actual code?) and often the return on investment is not obvious for the execs or customers paying the bills. If it is a reliable website you are after, you are better off with functional testing.

Zend Framework II comes with a full implementation of PHPUnit. The Zend\Test\PHPUnit library not just provides an interface with PHPUnit, it allows direct testing of controllers and views by bootstrapping. In this way the advantages of unit testing and functional testing are combined.

PHPUnit can be installed on Windows 7 by downloading a phar file from https://phar.phpunit.de/phpunit.phar into c:\bin as directory (create it) and renaming the phpunit.phar file to phpunit without any extension. If you use Xampp there is a good chance phpunit is already installed there but it may be an incorrect version (lot of complaints about missing PHP/CodeCoverage/Filter.php file). Make sure the c:\bin is added to the path in the environment variables before the Xampp path. PHPUnit can also be installed by Composer

The PHPUnit setup is easy thanks to the excellent ZF2 tutorial. The advantages are difficult to miss when it comes to testing the Orinoco River project.

In the code snippets below it is asserted the the index page returns a 200 status and that the name of the route is “home”. It is also asserted that the home page actually has a html, head and body tag.

public function testIndexActionCanBeAccessed()

    public function testIndexActionHasValidHtml()

The basic code changes (almost entirely based on the ZF2 tutorial) can be found here.

To run the test move to the module\Application\tests\phpunit folder on the command-line and execute the phpunit command. The result may look like this:

$ phpunit
PHPUnit 4.6.6 by Sebastian Bergmann and contributors.

Configuration read from C:\xampp\htdocs\zf2project\module\Application\tests\phpunit\phpunit.xml


Time: 976 ms, Memory: 16.00Mb
OK (5 tests, 19 assertions)


* http://framework.zend.com/manual/current/en/modules/zend.test.phpunit.html
* http://framework.zend.com/manual/current/en/tutorials/unittesting.html
* https://en.wikipedia.org/wiki/PHPUnit
* https://phpunit.de/manual/current/en/installation.html
* http://www.afewmorelines.com/mocking-user-identities-in-zf2-action-controller-unit-tests/