Prev Next

Chapter 16. Skeleton Generator

Generating a Test Case Class Skeleton

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.5.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 10) in the generated test case class.

Namespaced Classes and the Skeleton Generator

When you are using the skeleton generator to generate code based on a class that is declared in a namespace you have to provide the qualified name of the class as well as the path to the source file it is declared in.

For instance, for a class Bar that is declared in the Foo namespace you need to invoke the skeleton generator like this:

phpunit --skeleton-test Foo\Bar Bar.php

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

phpunit --verbose CalculatorTest
PHPUnit 3.5.0 by Sebastian Bergmann.

CalculatorTest
I


Time: 0 seconds

There was 1 incomplete test:

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

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

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.5.0 by Sebastian Bergmann.

....

Time: 0 seconds


OK (4 tests, 4 assertions)

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(...))
@assert (...) > XassertGreaterThan(X, method(...))
@assert (...) >= XassertGreaterThanOrEqual(X, method(...))
@assert (...) < XassertLessThan(X, method(...))
@assert (...) <= XassertLessThanOrEqual(X, method(...))
@assert (...) throws X@expectedException X


Generating a Class Skeleton from a Test Case Class

When you are doing Test-Driven Development (see Chapter 13) and write your tests before the code that the tests exercise, PHPUnit can help you generate class skeletons from test case classes.

Following the convention that the tests for a class Unit are written in a class named UnitTest, the test case class' source is searched for variables that reference objects of the Unit class and analyzing what methods are called on these objects. For example, take a look at Example 16.4 which has been generated based on the analysis of Example 16.3.

Example 16.3: The BowlingGameTest class

<?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());
    }
}
?>


Example 16.4: The generated BowlingGame class skeleton

<?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.');
    }
}
?>


Prev Next
1. Automating Tests
2. PHPUnit's Goals
3. Installing PHPUnit
4. Writing Tests for PHPUnit
Test Dependencies
Data Providers
Testing Exceptions
Testing PHP Errors
5. The Command-Line Test Runner
6. Fixtures
More setUp() than tearDown()
Variations
Sharing Fixture
Global State
7. Organizing Tests
Composing a Test Suite Using the Filesystem
Composing a Test Suite Using XML Configuration
Using the TestSuite Class
8. TestCase Extensions
Testing Output
9. Database Testing
Data Sets
Flat XML Data Set
XML Data Set
CSV Data Set
Replacement Data Set
Operations
Database Testing Best Practices
10. Incomplete and Skipped Tests
Incomplete Tests
Skipping Tests
11. Test Doubles
Stubs
Mock Objects
Stubbing and Mocking Web Services
Mocking the Filesystem
12. Testing Practices
During Development
During Debugging
13. Test-Driven Development
BankAccount Example
14. Code Coverage Analysis
Specifying Covered Methods
Ignoring Code Blocks
Including and Excluding Files
15. Other Uses for Tests
Agile Documentation
Cross-Team Tests
16. Skeleton Generator
Generating a Test Case Class Skeleton
Generating a Class Skeleton from a Test Case Class
17. PHPUnit and Selenium
Selenium RC
PHPUnit_Extensions_SeleniumTestCase
18. Logging
Test Results (XML)
Test Results (TAP)
Test Results (JSON)
Code Coverage (XML)
19. Build Automation
Apache Ant
Apache Maven
Phing
20. Continuous Integration
Atlassian Bamboo
CruiseControl
phpUnderControl
21. PHPUnit API
Overview
PHPUnit_Framework_Assert
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInstanceOf()
assertInternalType()
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertType()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
PHPUnit_Framework_Test
PHPUnit_Framework_TestCase
PHPUnit_Framework_TestSuite
PHPUnit_Framework_TestResult
Package Structure
22. Extending PHPUnit
Subclass PHPUnit_Framework_TestCase
Assert Classes
Subclass PHPUnit_Extensions_TestDecorator
Implement PHPUnit_Framework_Test
Subclass PHPUnit_Framework_TestResult
Implement PHPUnit_Framework_TestListener
New Test Runner
A. Assertions
B. Annotations
@assert
@author
@backupGlobals
@backupStaticAttributes
@covers
@dataProvider
@depends
@expectedException
@expectedExceptionCode
@expectedExceptionMessage
@group
@outputBuffering
@runTestsInSeparateProcesses
@runInSeparateProcess
@test
@testdox
@ticket
C. The XML Configuration File
PHPUnit
Test Suites
Groups
Including and Excluding Files for Code Coverage
Logging
Test Listeners
Setting PHP INI settings, Constants and Global Variables
Configuring Browsers for Selenium RC
D. Index
E. Bibliography
F. Copyright