Prev Next

Chapter 16. Skeleton Generator

The PHPUnit Skeleton Generator is a tool that can generate skeleton test classes from production code classes and vice versa. It can be installed using the following command:

pear install phpunit/PHPUnit_SkeletonGenerator

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. The PHPUnit Skeleton Generator 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-skelgen --test Calculator
PHPUnit Skeleton Generator 1.0.0 by Sebastian Bergmann.

Wrote skeleton for "CalculatorTest" to "/home/sb/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.

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 Calculator that is declared in the project namespace you need to invoke the skeleton generator like this:

phpunit-skelgen --test -- "project\Calculator" Calculator.php
PHPUnit Skeleton Generator 1.0.0 by Sebastian Bergmann.

Wrote skeleton for "project\CalculatorTest" to "/home/sb/CalculatorTest.php".

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

phpunit --bootstrap Calculator.php --verbose CalculatorTest
PHPUnit 3.8.0 by Sebastian Bergmann.

I

Time: 0 seconds, Memory: 3.50Mb

There was 1 incomplete test:

1) CalculatorTest::testAdd
This test has not been implemented yet.

/home/sb/CalculatorTest.php:38
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 --bootstrap Calculator.php --verbose CalculatorTest
PHPUnit 3.8.0 by Sebastian Bergmann.

....

Time: 0 seconds, Memory: 3.50Mb

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

Annotation Transformed to
@assert (...) == X assertEquals(X, method(...))
@assert (...) != X assertNotEquals(X, method(...))
@assert (...) === X assertSame(X, method(...))
@assert (...) !== X assertNotSame(X, method(...))
@assert (...) > X assertGreaterThan(X, method(...))
@assert (...) >= X assertGreaterThanOrEqual(X, method(...))
@assert (...) < X assertLessThan(X, method(...))
@assert (...) <= X assertLessThanOrEqual(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 12) 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());
}
}
?>

phpunit-skelgen --class BowlingGameTest
PHPUnit Skeleton Generator 1.0.0 by Sebastian Bergmann.

Wrote skeleton for "BowlingGame" to "./BowlingGame.php".

Example 16.4: The generated BowlingGame class skeleton

<?php
/**
* Generated by PHPUnit_SkeletonGenerator on 2012-01-09 at 16:55:58.
*/
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.');
}
}
?>

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

phpunit --bootstrap BowlingGame.php BowlingGameTest
PHPUnit 3.8.0 by Sebastian Bergmann.

E

Time: 0 seconds, Memory: 3.50Mb

There was 1 error:

1) BowlingGameTest::testScoreForGutterGameIs0
RuntimeException: Not yet implemented.

/home/sb/BowlingGame.php:13
/home/sb/BowlingGameTest.php:14
/home/sb/BowlingGameTest.php:20

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
Prev Next
1. Automating Tests
2. PHPUnit's Goals
3. Installing PHPUnit
PEAR
Composer
PHP Archive (PHAR)
Optional packages
Upgrading
4. Writing Tests for PHPUnit
Test Dependencies
Data Providers
Testing Exceptions
Testing PHP Errors
Testing Output
Assertions
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertContainsOnlyInstancesOf()
assertCount()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInstanceOf()
assertInternalType()
assertJsonFileEqualsJsonFile()
assertJsonStringEqualsJsonFile()
assertJsonStringEqualsJsonString()
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
Error output
Edge cases
5. The Command-Line Test Runner
Command-Line switches
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
8. Database Testing
Supported Vendors for Database Testing
Difficulties in Database Testing
The four stages of a database test
1. Clean-Up Database
2. Set up fixture
3–5. Run Test, Verify outcome and Teardown
Configuration of a PHPUnit Database TestCase
Implementing getConnection()
Implementing getDataSet()
What about the Database Schema (DDL)?
Tip: Use your own Abstract Database TestCase
Understanding DataSets and DataTables
Available Implementations
Beware of Foreign Keys
Implementing your own DataSets/DataTables
The Connection API
Database Assertions API
Asserting the Row-Count of a Table
Asserting the State of a Table
Asserting the Result of a Query
Asserting the State of Multiple Tables
Frequently Asked Questions
Will PHPUnit (re-)create the database schema for each test?
Am I required to use PDO in my application for the Database Extension to work?
What can I do, when I get a Too much Connections Error?
How to handle NULL with Flat XML / CSV Datasets?
9. Incomplete and Skipped Tests
Incomplete Tests
Skipping Tests
Skipping Tests using @requires
10. Test Doubles
Stubs
Mock Objects
Mocking Traits and Abstract Classes
Stubbing and Mocking Web Services
Mocking the Filesystem
11. Testing Practices
During Development
During Debugging
12. Test-Driven Development
BankAccount Example
13. Behaviour-Driven Development
BowlingGame Example
14. Code Coverage Analysis
Specifying Covered Methods
Ignoring Code Blocks
Including and Excluding Files
Edge cases
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 Server
Installation
PHPUnit_Extensions_Selenium2TestCase
PHPUnit_Extensions_SeleniumTestCase
18. Logging
Test Results (XML)
Test Results (TAP)
Test Results (JSON)
Code Coverage (XML)
Code Coverage (TEXT)
19. Extending PHPUnit
Subclass PHPUnit_Framework_TestCase
Write custom assertions
Implement PHPUnit_Framework_TestListener
Subclass PHPUnit_Extensions_TestDecorator
Implement PHPUnit_Framework_Test
A. Assertions
B. Annotations
@author
@after
@afterClass
@backupGlobals
@backupStaticAttributes
@before
@beforeClass
@codeCoverageIgnore*
@covers
@coversNothing
@dataProvider
@depends
@expectedException
@expectedExceptionCode
@expectedExceptionMessage
@group
@outputBuffering
@preserveGlobalState
@requires
@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