Generating Code from Tests

Sebastian Bergmann » 12 March 2008 » in New Features » 1 Comment

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.

Defined tags for this entry:

Trackback specific URI for this entry

1 Comment to "Generating Code from Tests"

Display comments as (Linear | Threaded)
  1. PHP Encoder
    02/04/2008 at 19:37 Permalink
    Looks like phpunit is very useful and about the time to get used to it. PHP developers need to become more professional!

    Reply

0 Trackbacks to "Generating Code from Tests"

  1. No Trackbacks

Add Comment


To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Submitted comments will be subject to moderation before being displayed.