Chapter 6. Organizing Test Suites

One of the goals of PHPUnit (see Chapter 2) is that tests should be composable: we want to be able to run any number or combination of tests together, for instance all tests for the whole project, or the tests for all classes of a component that is part of the project, or just the tests for one class or a one method.

The PHPUnit_Framework_TestSuite class of the PHPUnit framework allows us to organize tests into a hierarchy of test suites. Let us look at PHPUnit's own test suite as an example.

Example 6.1 shows a cut-down version of Tests/AllTests.php, Example 6.2 a cut-down version of Tests/Framework/AllTests.php.

Example 6.1: The AllTests class

<?php
if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'AllTests::main');
}
 
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/TextUI/TestRunner.php';
 
require_once 'Framework/AllTests.php';
// ...
 
class AllTests
{
    public static function main()
    {
        PHPUnit_TextUI_TestRunner::run(self::suite());
    }
 
    public static function suite()
    {
        $suite = new PHPUnit_Framework_TestSuite('PHPUnit');
 
        $suite->addTest(Framework_AllTests::suite());
        // ...
 
        return $suite;
    }
}
 
if (PHPUnit_MAIN_METHOD == 'AllTests::main') {
    AllTests::main();
}
?>


Example 6.2: The Framework_AllTests class

<?php
if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'Framework_AllTests::main');
}
 
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/TextUI/TestRunner.php';
 
require_once 'Framework/AssertTest.php';
// ...
 
class Framework_AllTests
{
    public static function main()
    {
        PHPUnit_TextUI_TestRunner::run(self::suite());
    }
 
    public static function suite()
    {
        $suite = new PHPUnit_Framework_TestSuite('PHPUnit Framework');
 
        $suite->addTestSuite('Framework_AssertTest');
        // ...
 
        return $suite;
    }
}
 
if (PHPUnit_MAIN_METHOD == 'Framework_AllTests::main') {
    Framework_AllTests::main();
}
?>


The Framework_AssertTest class is a standard test case that extends PHPUnit_Framework_TestCase.

Running Tests/AllTests.php uses the TextUI test runner to run all tests while running Tests/Framework/AllTests.php runs only the tests for the PHPUnit_Framework_* classes.

This example shows the PHPUnit test suite running:

php AllTests.php
PHPUnit 3.1.0 by Sebastian Bergmann.

.........................................
.........................................
.........................................
.........................................
......SSSSSS.....

Time: 00:04


OK, but incomplete or skipped tests!
Tests: 181, Skipped: 6.