Chapter 16. Skeleton Generator

When you are writing tests for existing code, you have to write the same code fragments such as

public function testMethod()
{
}

over and over again. PHPUnit can help you by analyzing the code of the existing class and generating a skeleton test-case class for it.

Example 16.1: The Calculator class

<?php
class Calculator
{
    public function add($a, $b)
    {
        return $a + $b;
    }
}
?>


The following example shows how to generate a skeleton test class for a class named Calculator (see Example 16.1).

phpunit --skeleton Calculator
PHPUnit 3.1.0 by Sebastian Bergmann.

Wrote test class skeleton for Calculator to CalculatorTest.php.

For each method in the original class, there will be an incomplete test-case (see Chapter 9) in the generated test-case class.

Below is the output of running the generated test-case class.

phpunit --verbose CalculatorTest
PHPUnit 3.1.0 by Sebastian Bergmann.

I

Time: 00:00

There was 1 incomplete test:

1) testAdd(CalculatorTest)
This test has not been implemented yet.
/home/sb/CalculatorTest.php:55

OK, but incomplete or skipped tests!
Tests: 1, Incomplete: 1.

Annotations

You can use @assert annotation in the documentation block of a method to automatically generate simple, yet meaningful tests instead of incomplete test-cases. Example 16.2 shows an example.

Example 16.2: The Calculator class with @assert annotations

<?php
class Calculator
{
    /**
     * @assert (0, 0) == 0
     * @assert (0, 1) == 1
     * @assert (1, 0) == 1
     * @assert (1, 1) == 2
     */
    public function add($a, $b)
    {
        return $a + $b;
    }
}
?>


Each method in the original class is checked for @assert annotations. These are transformed into test code such as

    /**
     * Generated from @assert (0, 0) == 0.
     */
    public function testAdd() {
        $o = new Calculator;
        $this->assertEquals(0, $o->add(0, 0));
    }

Below is the output of running the generated test-case class.

phpunit CalculatorTest
PHPUnit 3.1.0 by Sebastian Bergmann.

....

Time: 00:00


OK (4 tests)

Table 16.1 shows the supported variations of the @assert annotation and how they are transformed into test code.

Table 16.1. Supported variations of the @assert annotation

AnnotationTransformed to
@assert (...) == XassertEquals(X, method(...))
@assert (...) != XassertNotEquals(X, method(...))
@assert (...) === XassertSame(X, method(...))
@assert (...) !== XassertNotSame(X, method(...))