Test Driven Development
By Marcus Baker2004-01-25
Tests as documentation
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 A long message\n")),
array('a' => 'A long message'));
}
function testMultipleKeyValuePairs() {
$parser = &new ConfigurationParser();
$this->assertEqual(
$parser->parse(array("a A\n", "b\tB\n")),
array('a' => 'A', 'b' => 'B'));
}
function testBlankLinesAreIgnored() {
$parser = &new ConfigurationParser();
$this->assertEqual(
$parser->parse(array("\n", "key value\n")),
array('key' => 'value'));
}
function testCommentLinesAreIgnored() {
$parser = &new ConfigurationParser();
$this->assertEqual(
$parser->parse(array("# A comment\n", "key value\n")),
array('key' => 'value'));
}
}
Notice how the test case describes the behaviour. Once you are used to reading test cases you can use them as an executable specification of the code. Unlike coments they cannot lie.
Now look what has happened to the code...
class ConfigurationParser {
function parse($lines) {
$values = array();
foreach ($lines as $line) {
if (preg_match('/^\s*#/', $line)) {
continue;
}
if (preg_match('/^(\w+)\s+(.*)/', $line, $matches)) {
$values[$matches[1]] = trim($matches[2]);
}
}
return $values;
}
}
That crucial regular expression has gone through several refinements. Even though I was able to code the first version without breaking the tests, I found plenty of bugs when I added blank lines and comments into the mix. Just goes to show what happens if you don't test.
Tutorial pages:
|
|
|||||||||
You might also want to check these out:
|
Leave a Comment on "Test Driven Development"
You must be logged in to post a comment.
Link to This Tutorial Page!

