Generating Code from Tests
When you are practicing Test-First Programming, PHPUnit can help you generate class skeletons from test case classes.
<?php
class BowlingGameTest extends PHPUnit_Framework_TestCase
{
protected $game;
protected function setUp()
{
$this->game = new BowlingGame;
}
protected function rollMany($n, $pins)
{
for ($i = 0; $i < $n; $i++) {
$this->game->roll($pins);
}
}
public function testScoreForGutterGameIs0()
{
$this->rollMany(20, 0);
$this->assertEquals(0, $this->game->score());
}
}
?>
Following the convention that the tests for a class BowlingGame (see below) are written in a class named BowlingGameTest (see above), the test case class' source is searched for variables that reference objects of the BowlingGame class and analyzing what methods are called on these objects.
<?php
/**
* Generated by PHPUnit on 2008-03-10 at 17:18:33.
*/
class BowlingGame
{
/**
* @todo Implement roll().
*/
public function roll()
{
// Remove the following line when you implement this method.
throw new RuntimeException('Not yet implemented.');
}
/**
* @todo Implement score().
*/
public function score()
{
// Remove the following line when you implement this method.
throw new RuntimeException('Not yet implemented.');
}
}
?>
The code of the BowlingGame class (see above) has been generated from the code of the BowlingGameTest using phpunit --skeleton-class BowlingGameTest.
This is a new feature in PHPUnit 3.3.
