Skip to main content

Testing your code

Perhaps no other coding practice is as important as testing your code. Also in the nature of Business Development, where parts of your code always change on the request of a client (including Management), or even when you want to make your code run with better performance, Automated tests are highly needed, you can't just spread your print statements all over your code every time you need to test it.
With automated tests, you can just be sure that your interface is not broken after some change, you just run your tests, if they succeed, you know that you didn't break your code (this means you should right good tests).
Let's start by a simple example, Imagine that we have been asked to test PHP's built-in Array. One bit of functionality to test is the function sizeof(). For a newly created array we expect the sizeof() function to return 0. After we add an element, sizeof() should return 1. (I know it's not a big deal, but it's just an example).
you can do it with simple print statements (i.e. print (1 == sizeof($myArray) ? "OK":"Failure").PHP_EOL; ), but here we are going to do it by using an assertion function.

< ?php
$fixture = Array();
assertTrue(sizeof($fixture) == 0);

$fixture[] = "element";
assertTrue(sizeof($fixture) == 1);

function assertTrue($condition) {
if (!$condition) {
throw new Exception("Assertion failed.");

Well, we could know if something went wrong if some Exception was raised, of course assertTrue is not the only thing you want to do, UnitTesting has gone far beyond that, usually UnitTesting frameworks provide a whole lot of features that you need for your testing.
Lot's of Testing frameworks are available for PHP, I'm going to point to 2 of them, the first one is SimpleTest (, it's written in PHP 4 (Although they are going to migrate to PHP 5 when they reach version 2), so you can use it on both PHP 4 and 5 programs, also it includes a nice HTML reporter for some good looking html results the same test above could be written using this framework as:

< ?php
require_once 'simpletest/unit_tester.php';
require_once 'simpletest/reporter.php';

class TestingFixtureArray extends UnitTestCase {
function TestArray() {
$this->UnitTestCase("Testing Fixture Array");
$fixture = Array();
$this->assertTrue(sizeof($fixture) == 0);

$fixture[] = "element";
$this->assertTrue(sizeof($fixture) == 1);


//run the Test
$test = new TestingFixtureArray();
$test->run(new HtmlReporter());

Another Well know testing framework is known as PHPUnit2 (, it's available through the PEAR Repository, you can install it as
$ pear install PHPUnit2
It's written in PHP 5, and is so widely used within PHP Developers, a good resource for learning how to use it is the free available online book PHPUnit Pocket Guide (, the same example could be:

< ?php
require_once 'PHPUnit2/Framework/TestCase.php';

class ArrayTest extends PHPUnit2_Framework_TestCase {
public function testNewArrayIsEmpty() {
// Create the Array fixture.
$fixture = Array();

// Assert that the size of the Array fixture is 0.
$this->assertEquals(0, sizeof($fixture));


public function testArrayContainsAnElement() {
// Create the Array fixture.
$fixture = Array();

// Add an element to the Array fixture.
$fixture[] = 'Element';

// Assert that the size of the Array fixture is 1.
$this->assertEquals(1, sizeof($fixture));


and you can run it on command line as
$ phpunit ArrayTest

Additional benefits that you can realize by thoroughly testing your code:

  • Testing forces you to write code that is easily testable. This leads to looser coupling, flexible designs, and good modularity.

  • Writing tests forces you to explicitly clarify your expectations of how your code is to behave, distilling your design into sharper focus from the beginning. Writing tests forces you to consider the universe of possible inputs and the corresponding results.

  • Tests are very explicit way of communicating the intent of your code. In other words, test cases act as example and documentation, showing exactly how a given class, method, or function should behave. A test case defines how code works in a non-ambiguous way.

Finally, if your test suite - your set of test cases - is very thorough, you can say your code is complete when all of your test pass. Interestingly, that notion is one of the hallmarks of Test Driven Development.
Test Driven Development (TDD), also referred to as Test First Coding, is a methodology that takes testing one step further: you write your tests before you ever write any code. A nice, brief summary of the tenants of TDD is available at, and a good introductory book on the strategy is "Test Driven Development: By Example" by Kent Beck. (The book's examples are in Java, but it's a quick read and gives you a very good overview and introduction to the subject.)

Agile Development
Recently, unit testing - in particular Test Driven Development - has been associated with agile Development methodologies such as Extreme Programming (XP)g that focus on rapid iterations of releasing functional code to customers and welcoming changing customer requirements as a natural part of the development process. Some good online resources for learning about agile development include:

[tags] automated tests, sizeof, business development, array, functionality, element, nature of business, interface[/tags]


  1. That is indeed true.
    The worset thing anyone could do about a mistake is to lie about it.

  2. PHPUnit is no longer named "PHPUnit2" and is no longer hosted in PEAR. Please see its website for updated installation instructions and for details on how to write and run tests for/with PHPUnit.

  3. Nice summary - it might be noteworthy that for testing frontends instead of APIs, using Selenium will ease test creation and automation quite a bit. Selenium integration is available with the latest PHPUnit releases.

    PHPUnit, by the way, is no longer hosted in PEAR, so a simple "pear install PHPUnit2" won't do any longer - you'll have to register the appropriate channel server first. I'm not sure if PHPUnit even exists in the official PEAR channel anymore - if it does, it's an old version that won't likely receive any more updates.

  4. Hi,
    what plugin you are using for code display?

  5. There is also the mostly unknown function assert, which is available in standard distribution. It also has the advantage to be totally removed with the simple switch of a PHP directive.


  6. PHPUnit3 has been launched and has many many new things to try

  7. I like Unittests and love PHPUnit, a tool that needs more advocacy .. its just a very productive test tool. I had great results writing some thousand tests with it ;)


  8. Thanks for your replys
    Bergmann, thanks for the update, I haven't checked the pear site for quite some time, the installation instructions now would be:
    $ pear channel-discover
    $ pear install phpunit/PHPUnit
    Seguy, unit testing is not just about assertions, it's a lot more.
    Rodríguez, thanks for the update, I guess I'm going to try it real soon.

  9. Vaidas Žilionis,
    We use CoolCode plugin, it's awesome, you should give it a try.


Post a Comment

Popular posts from this blog

اهم التطورات العلمية في العام ٢٠١٩

Dear Microsoft : It's over. Our relationship just hasn't been working for a while, and now, this is it. I'm leaving you for another Operating system. I know this isn't a good time--you're down with yet another virus. I do hope you feel better soon--really, I do--but I, too, have to move on with my life. Fact is, in the entire time I've known you, you seem to always have a virus or an occasional worm. You should really see a doctor. That said, I just can't continue with this relationship any longer. I know you say you'll fix things, that next time it'll go better--but that's what you said the last time--and the time before that. Each time I believed you. Well, not any longer. You cheater! The truth is there's nothing more you can say to make things better. I know about your secret marriage to patent. You say you two are not seeing each other anymore, but I just don't believe it. You say you can live without patent, and I've heard that

Saddam's novel to be published next week

AMMAN, Jordan: Saddam Hussein's family will publish next week a novel written by the ousted Iraqi leader before the US-led war on Iraq, his daughter said on Friday. "Ekhroj minha ya mal'un" whose title could be translated into "Get out, damned one" tells the story of a man called Ezekiel who plots to overthrow a town's sheik, but is defeated in his quest by the sheik's daughter and an Arab warrior. The story is apparently a metaphor for a Zionist-Christian plot against Arabs and Muslims. Ezekiel is meant to symbolize the Jews. Raghad Saddam Hussein said her father finished the novel on March 18, 2003 -- a day before the US-led war on Iraq began -- and had expressed a wish to publish the book under his name. The three other novels he wrote were simply signed "Its author." "It was my father's will to publish this book," Raghad said in a telephone interview. Read more An Iraqi artist designed the book's cover, she said, and a