#native_company# #native_desc#
#native_cta#

Test Driven Development in PHP Page 2

By Marcus Baker
on February 3, 2004

Writing a Test

It’s actually not so simple to write a test, as to work like a well oiled machine the test has to be automated. You are going to run this test many many times. Not just when writing the tested code, but also when writing other unrelated code to make sure you haven’t broken anything. This safety net is called regression testing. Every time you change any code, run the whole test suite for the whole application.
The tests must also be quick. Not just physically running quickly, but also saying very concisely and clearly that the tests have passed or failed. Print statements will not cut it. Only you will know what the correct output of your print is, and trawling through pages of output will break your concentration on the task in hand anyway.
Beck has come to the rescue again. Along with Eric Gamma he is the author of JUnit. JUnit tests are organised into test cases, which are actually just subclasses of a test case class, and output is a simple red or green bar. The classes can be grouped together into test suites very easily and there are many ways of customising this infrastructure. Tests are easy to write, because you are testing in the same language as the code, Java here.
So elegant is this system that it has been ported to just about every other OO language, including PHP. I am actually going to use SimpleTest for the examples that follow. I have to admit slight bias here as I wrote the thing after some disaffection with the various early PHPUnits. If you use a PHPUnit (Sebastian Bergmann’s is the most developed), then for the examples that follow you should only have to make slight modifications to the code.
Of course we need a problem to solve. I am going to build a simple configuration file parser that accepts text in this format…
# A comment
#
some_message          Hello there
a_file                /var/stuff
That is, simple white space separated tagged constants. For most projects this type of configuration file is more than enough.
So we have a simple class to parse this data into a hash? Shall we create the class now? If you think so then I am afraid you get a slap on the wrist. We always write the test first and we let the test tell us whether we need a class or not. By having the tests drive the development we make sure that we don’t over design or simply write tests to justify our predujices.
Let’s write a test…

1
|
2
|
3
|
4
|
5
|
6
|
7