Monday, February 22

Using PhpUnit with NetBeans

With the boom of TDD is amazing how slowly the IDEs are integrating unit testing to their features, for PHP I've only found a few, and the best result (for me at least) was using NetBeans.

Here we'll cover how to install PHPunit and integrate it into NetBeans

First, as always install some application we'll need in the future
$ sudo apt-get install php5-dev php-pear

If you installed xdebug from ubuntu repositories you'll need to remove it
$ sudo apt-get remove php5-xdebug

Now discover phpunit servers
$ sudo pear channel-discover
$ sudo pear channel-discover

And install it
$ sudo pear install --alldeps phpunit/PHPUnit

I strongly recommend installing xdebug
$ sudo pecl install xdebug

Now that you have phpUnit installed just need to add some generic tests to your project, what I've used is

1. Create a tests directory on the project root
$ mkdir tests

2. Create a php file that will recursively load all the files in the directory and run a class of phpUnit to run all the classes loaded, some proposed content is displayed here.
$ kate allTests.php
//add the phpunit framework
require_once 'PHPUnit/Framework.php';

//including all the files available in the current directory
$filesIncluded = array();
includeRecurse('tests', $filesIncluded);

//generic class
class phpucAllTests
public static function suite()
$suite = new PHPUnit_Framework_TestSuite('Package');
foreach ($GLOBALS['filesIncluded'] as $fileincluded)
$filename = explode('.', $fileincluded);
return $suite;

3. Any file inside the tests directory should be something like:
class InstallJobTest extends PHPUnit_Framework_TestCase
public function testAapplyFilters()
//test the null query
$query = null;
$sql = $query->getSQL();
$this->assertRegExp('/^SELECT (.*) FROM InstallJob/', $sql);

//Testing club number filter

//Testing installation companies

Now that all the required files are created, it's time to test the phpUnit

Open a console and into your project directory run
$ phpunit tests/allTests.php

If all is working is time to use NetBeans

Select the project in the "Projects" panel and right click it, select "test" from the context menu.

A dialog will open prompting for a unit test folder, select the tests directory you created

Now below "Source Files" a new item called "Test Files" appear with the contents of the tests directory

To run the tests right click allTests.php file and select "run" from the context menu

NetBeans will display some useful information such as the code coverage, executed test cases, asserts, etc.