#native_company# #native_desc#
#native_cta#

Test Driven Development in PHP Page 4

By Marcus Baker
on February 3, 2004

Our First Test (at last!)
Here is our first test…

<?php

define
('SIMPLE_TEST''simpletest/');

require_once(
SIMPLE_TEST 'unit_tester.php');

require_once(
SIMPLE_TEST 'reporter.php');

require_once(
'../classes/config.php');

class ConfigurationTest extends UnitTestCase {

    function 
ConfigurationTest() {

        
$this->UnitTestCase();

    }

    function 
testNoLinesGivesEmptyHash() {

        
$parser = &new ConfigurationParser();

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

    }

}

$test = &new ConfigurationTest();

$test->run(new HtmlReporter());

?>



When a test case is run, it looks at it’s internals to see if it has any methods that start with the string test. If it has then it will attempt to execute those methods. Each test method can make various assertions with simple criteria for failure. Our assertIdentical() does an === comparison and issues a failure if it doesn’t match.
A successfuly completed test will run every one of these methods in turn and total the results of the assertions. If so much as a single one of the assertions fails, then the whole test suite fails. There is no such thing as a partially running suite, because there is no such thing as partially correct code.
Our test script doesn’t even get that far…
Warning: main(../classes/config.php) [function.main]: failed to create stream: No such file or directory in /home/marcus/articles/developerspot/test/config_test.php on line 5
 
Fatal error: main() [function.main]: Failed opening required ‘../classes/config.php’ (include_path=’/usr/local/lib/php:.:/home/marcus/projects/sourceforge’) in /home/marcus/articles/developerspot/test/config_test.php on line 5
When I said that we will code test first I really did mean write the test before any code. Even before creating the file.
To get the code legal we need a classes/config.php file with a ConfigurationParser class and a parse() method…

<?php

class ConfigurationParser {

    function 
parse() {

    }

}

?>



Having done this minimal step we have a running, but failing, test case…

configurationtest

Fail: testnolinesgivesemptyhash->Identical expectation [NULL] fails with [Array: 0 items] with type mismatch as [NULL] does not match [Array: 0 items]

1/1 test cases complete:
0 passes, 1 fails and 0 exceptions.
I am assuming that the parser will get a list of lines, probably from the PHP file() function, and output a hash of constants. An empty line list should produce an empty hash.
Can we code now? No need to hide your wrists, as yes, we can code on a failing test.

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