Debugging your phpunit test cases in CodeIgniter

I don’t know why it feels ironic, but it does. Sometimes I need to debug my phpunit test cases and it wasn’t very very self explanatory to understand how to set it up . The solution however, is quite easy.

I’ve previously written about how to enable the php debugger xdebug from a command line script. The end result from reading that article should be that you have a php5d command on your system that will trigger xdebug to hook into your IDE (mine is Sublime Text 2, yours may differ). For the rest of this article, I’m going to assume you have the php5d command available.

Next step is to prepare your test classes for execution via a php command rather than via the phpunit framework (don’t worry, it will be included). The solution to this was found at Stack Overflow (naturally, read it, it’s good), but I  found out that two simplifications can be made when used in CodeIgniter with CI_Unit.

The foundation of the StackOveflow trick is to make sure that a couple of PHPUnit classes are loaded, either via explicit statements as the sample suggests, or via the PHPUnit/Autoload functionality. Turns out that when bootstraping PHPUnit via CI_Unit, it already brings in PHPUnit/Autoload.php. That makes it one less requre_once statement to forget about.

The second simplification is to minimize the room for copy / paste related errors. As long as you are a bit obsessive with class names and make sure that your file name is always classname.php (so class FooTest is implemented in the file FooTest.php), then you can avoid typing the class name in one additional place. That’s exactly what I need to do myself to avoid hard to catch errors.

My test cases are now modeled after this template:

* Tests for the Foo class

class FooClassTest extends CIUnit_TestCase
static function main() 
  $suite = new PHPUnit_Framework_TestSuite( __CLASS__);
  PHPUnit_TextUI_TestRunner::run( $suite);

public function setUp()


public function testSomething()

if (!defined('PHPUnit_MAIN_METHOD')) {
  $class = str_replace('.php','', basename(__FILE__));

And to actually debug it (assuming that the above test class is stored in tests/lib and is naturally named FooClassTest.php), I type:

$ cd tests
$ php5d libs/FooClassTest.php

And to run it under PHPUnit, it’s works just as you’re used to already.


Leave a comment

Your email address will not be published. Required fields are marked *