#native_company# #native_desc#
#native_cta#

Test Driven Development in PHP Page 5

By Marcus Baker
on February 3, 2004

Minimal Code

The catch is that we are not going to design the code in any way at all. We are going to write only enough to pass the test. Here is the code…

<?php 

class ConfigurationParser {

    function 
parse() {

        return array();

    }

}

?>



This is after all the bare minimum to get to green. If you were tempted to plan ahead as to how implement a parser, then you might want to keep your wrists out of site after all. Our test has no trouble passing…

configurationtest

1/1 test cases complete:
1 passes, 0 fails and 0 exceptions.
If you are losing patience right now, don’t worry. The pace will now pick up.
The first test was just to get the structure up. We’ll now genuinely constrain the solution with a one line configuration…

<?php

class ConfigurationTest extends UnitTestCase {

    function 
ConfigurationTest() {

        
$this->UnitTestCase();

    }

    function 
testNoLinesGivesEmptyHash() {

        
$parser = &new ConfigurationParser();

        
$this->assertIdentical($parser->parse(array()), array());

    }

    function 
testKeyValuePair() {

        
$parser = &new ConfigurationParser();

        
$this->assertEqual(

                
$parser->parse(array("a An")),

                array(
'a' => 'A'));

    }

}

?>



First we’ll do whatever we can to get to green…

<?php

class ConfigurationParser {

    function 
parse($lines) {

        if (
$lines == array("a An")) {

            return array(
'a' => 'A');

        }

        return array();

    }

}

?>



This works, but the design sucks. Adding more if statements is hardly the solution for each test. It will only work for these tests, be repetitive and the code doesn’t really explain what we are trying to do. Let’s fix it next.

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