unit testing for php

testing your php applications

backend unit testing for your actual php code. here’s a quick intro to using simpletest to test your php applications.

simpletest is a php unit testing and web testing framework along the lines of junit and jwebunit. it provides a comprehensive set of apis for testing everything from your class methods to your ssl-secured authentication pages.

unit testing in php generally validates that individual sections of your source code are functioning as expected. as your project grows, it’s hard to remember what each and every module is responsible for, especially with multiple developers. unit tests help check that a function or method does what it’s meant to, and when run during a build process or around version control commits, can check that recent changes haven’t broken expected functionality.

let’s look at a simple simpletest example:

unittestcase('test of arithmetic');

function testaddition() {

$arithmetic = new arithmetic();

$result = $arithmetic->add(1,1);

$this->assertequal($result, 2);




simpletest provides php classes that serve as the ground work for unit testing. when we define a new unit test case – in this case, “testofarithmetic”, simpletest automatically works out what tests you’ve defined in order to run them. we then simple create new methods for our tests, run whatever logic we need and use assert calls to check that we have achieved our expected outcome. in this case, we want to assert that the return value of arithmetic::add(1, 1) equals 2.

this may seem rather lengthy for a single test, but additional tests can be added on in as little as a single line of code and an entire application can be quickly checked for reliability with just a few hundred lines of unit tests. once this is in place, we can run our unit tests by loading up this script in our browser, and if everything is in order, we see a nice and concise status page displaying the results of the tests.

of course, why write tests after you write your application code, when you could write it sooner and sooner, and maybe even before? that’s the approach of test driven development (tdd) – simpletest is perfectly happy with writing tests for code that doesn’t exist yet. tdd, from one of the guys who created extreme programming (xp), basically involves writing tests to define the design of code and then working away at the code till it passes the tests, and simpletest is a great way to achieve it in php.

simpletest is hosted on sourceforge, so head over and try it out. they’ve also got a great tutorial on their main project site.