Testing (during winter solstice)

By | 2008-12-24

What was I doing during the shortest day (in Northern Hemisphere) of the year?
Enjoying the “code coverage” used in testing, while traveling to my hometown by train for Xmas.
Testing, code coverage… what’s that? you ask. Let me explain.

A really important part of developing code is testing the code you write. It’s the way to verify your code really works. The easiest way to do so is inserting some “prints” here and there, to verify that variables store expected values. Or you can write an external program to stress your code with some inputs and verify expected outputs. But the best way is to use a testing tool for creating automated tests. Then you normally do some unit tests (that stress modules/objects) and test suites (that aggregates unit tests).

Until recently I didn’t use automated tests. But some months ago I discovered PHPUnit, and now I’m “safe”. Automated tests helps you and your team against careless modifications (made by this new internal, or by yourself in a bad day).

And what’s code coverage? Well, when you write tests, there is a way to see if your tests stress all the code lines: code coverage. But let me show you a really small example of this useful tool.

Imagine this function/method:

function isChristmas($day,$month)
{
    if($day==25 && $month==12){
        return "Merry Christmas";
    }else{
        return "Have a good day";
    }
}

And this (obviously uncompleted) test:

public function testChristmas()
{
    $this->assertEquals("Have a good day",isChristmas(12,12));
    $this->assertEquals("Have a good day",isChristmas(28,02));
}

When you launch PHPUnit and ask for a code coverage analysis in HTML, you get something like this (click to see it fullsize):
Code coverage with PHPUnit
Isn’t this wonderful? You get a lot of information! You quickly discover ways to improve your tests and sometimes your source code… how could’ve lived without this?

Merry Christmas, by the way!

One thought on “Testing (during winter solstice)

  1. Julio (padre)

    Que tengas un buen día, y … por supuesto noche. No es día 25, y mes 12 (no se cumplen ambos).

Comments are closed.