Chapter21.PHPUnit API

For most uses, PHPUnit has a simple API: subclass PHPUnit_Framework_TestCase for your test cases and call assertTrue() or assertEquals(). However, for those of you who would like to look deeper into PHPUnit, here are all of its published methods and classes.

Overview

Most of the time, you will encounter five classes or interfaces when you are using PHPUnit:

PHPUnit_Framework_Assert

A collection of static methods for checking actual values against expected values.

PHPUnit_Framework_Test

The interface of all objects that act like tests.

PHPUnit_Framework_TestCase

A single test.

PHPUnit_Framework_TestSuite

A collection of tests.

PHPUnit_Framework_TestResult

A summary of the results of running one or more tests.

Figure 21.1 shows the relationship of the five basic classes and interfaces in PHPUnit: PHPUnit_Framework_Assert, PHPUnit_Framework_Test, PHPUnit_Framework_TestCase, PHPUnit_Framework_TestSuite, and PHPUnit_Framework_TestResult.

Figure21.1.The five basic classes and interfaces in PHPUnit

The five basic classes and interfaces in PHPUnit


PHPUnit_Framework_Assert

Most test cases written for PHPUnit are derived indirectly from the class PHPUnit_Framework_Assert, which contains methods for automatically checking values and reporting discrepancies. The methods are declared static, so you can write design-by-contract style assertions in your methods and have them reported through PHPUnit (Example 21.1).

Example 21.1: Design-by-Contract Style Assertions

<?php
require_once 'PHPUnit/Framework.php';
 
class Sample
{
    public function aSampleMethod($object)
    {
        PHPUnit_Framework_Assert::assertNotNull($object);
    }
}
 
$sample = new Sample;
$sample->aSampleMethod(NULL);
?>
Fatal error: Uncaught exception 'PHPUnit_Framework_ExpectationFailedException'
with message 'Failed asserting that <null> is not identical to <null>.'


Most of the time, though, you'll be checking the assertions inside of tests.

There are two variants of each of the assertion methods: one takes a message to be displayed with the error as a parameter, and one does not. The optional message is typically displayed when a failure is displayed, which can make debugging easier.

Example 21.2: Using assertions with messages

<?php
require_once 'PHPUnit/Framework.php';
 
class MessageTest extends PHPUnit_Framework_TestCase
{
    public function testMessage()
    {
        $this->assertTrue(FALSE, 'This is a custom message.');
    }
}
?>


The following example shows the output you get when you run the testMessage() test from Example 21.2, using assertions with messages:

phpunit MessageTest.php
PHPUnit 3.1.0 by Sebastian Bergmann.

F

Time: 00:00
There was 1 failure:
1) testMessage(MessageTest)
This is a custom message.
Failed asserting that <boolean:false> is identical to <boolean:true>.
/home/sb/MessageTest.php:8

FAILURES!
Tests: 1, Failures: 1.

Table 21.1 shows all the varieties of assertions.

Table21.1.Assertions

AssertionMeaning
void assertTrue(bool $condition)Reports an error if $condition is FALSE.
void assertTrue(bool $condition, string $message)Reports an error identified by $message if $condition is FALSE.
void assertFalse(bool $condition)Reports an error if $condition is TRUE.
void assertFalse(bool $condition, string $message)Reports an error identified by $message if $condition is TRUE.
void assertNull(mixed $variable)Reports an error if $variable is not NULL.
void assertNull(mixed $variable, string $message)Reports an error identified by $message if $variable is not NULL.
void assertNotNull(mixed $variable)Reports an error if $variable is NULL.
void assertNotNull(mixed $variable, string $message)Reports an error identified by $message if $variable is NULL.
void assertSame(object $expected, object $actual)Reports an error if the two variables $expected and $actual do not reference the same object.
void assertSame(object $expected, object $actual, string $message)Reports an error identified by $message if the two variables $expected and $actual do not reference the same object.
void assertSame(mixed $expected, mixed $actual)Reports an error if the two variables $expected and $actual do not have the same type and value.
void assertSame(mixed $expected, mixed $actual, string $message)Reports an error identified by $message if the two variables $expected and $actual do not have the same type and value.
void assertNotSame(object $expected, object $actual)Reports an error if the two variables $expected and $actual reference the same object.
void assertNotSame(object $expected, object $actual, string $message)Reports an error identified by $message if the two variables $expected and $actual reference the same object.
void assertNotSame(mixed $expected, mixed $actual)Reports an error if the two variables $expected and $actual have the same type and value.
void assertNotSame(mixed $expected, mixed $actual, string $message)Reports an error identified by $message if the two variables $expected and $actual have the same type and value.
void assertAttributeSame(object $expected, string $actualAttributeName, object $actualObject)Reports an error if $actualObject->actualAttributeName and $actual do not reference the same object. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeSame(object $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if $actualObject->actualAttributeName and $actual do not reference the same object. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeSame(mixed $expected, string $actualAttributeName, object $actualObject)Reports an error if $actualObject->actualAttributeName and $actual do not have the same type and value. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeSame(mixed $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if $actualObject->actualAttributeName and $actual do not have the same type and value. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotSame(object $expected, string $actualAttributeName, object $actualObject)Reports an error if $actualObject->actualAttributeName and $actual reference the same object. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotSame(object $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if $actualObject->actualAttributeName and $actual reference the same object. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotSame(mixed $expected, string $actualAttributeName, object $actualObject)Reports an error if $actualObject->actualAttributeName and $actual have the same type and value. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotSame(mixed $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if $actualObject->actualAttributeName and $actual have the same type and value. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertEquals(array $expected, array $actual)Reports an error if the two arrays $expected and $actual are not equal.
void assertEquals(array $expected, array $actual, string $message)Reports an error identified by $message if the two arrays $expected and $actual are not equal.
void assertNotEquals(array $expected, array $actual)Reports an error if the two arrays $expected and $actual are equal.
void assertNotEquals(array $expected, array $actual, string $message)Reports an error identified by $message if the two arrays $expected and $actual are equal.
void assertEquals(float $expected, float $actual, '', float $delta = 0)Reports an error if the two floats $expected and $actual are not within $delta of each other.
void assertEquals(float $expected, float $actual, string $message, float $delta = 0)Reports an error identified by $message if the two floats $expected and $actual are not within $delta of each other.
void assertNotEquals(float $expected, float $actual, '', float $delta = 0)Reports an error if the two floats $expected and $actual are within $delta of each other.
void assertNotEquals(float $expected, float $actual, string $message, float $delta = 0)Reports an error identified by $message if the two floats $expected and $actual are within $delta of each other.
void assertEquals(string $expected, string $actual)Reports an error if the two strings $expected and $actual are not equal. The error is reported as the delta between the two strings.
void assertEquals(string $expected, string $actual, string $message)Reports an error identified by $message if the two strings $expected and $actual are not equal. The error is reported as the delta between the two strings.
void assertNotEquals(string $expected, string $actual)Reports an error if the two strings $expected and $actual are equal.
void assertNotEquals(string $expected, string $actual, string $message)Reports an error identified by $message if the two strings $expected and $actual are equal.
void assertEquals(mixed $expected, mixed $actual)Reports an error if the two variables $expected and $actual are not equal.
void assertEquals(mixed $expected, mixed $actual, string $message)Reports an error identified by $message if the two variables $expected and $actual are not equal.
void assertNotEquals(mixed $expected, mixed $actual)Reports an error if the two variables $expected and $actual are equal.
void assertNotEquals(mixed $expected, mixed $actual, string $message)Reports an error identified by $message if the two variables $expected and $actual are equal.
void assertAttributeEquals(array $expected, string $actualAttributeName, object $actualObject)Reports an error if the two arrays $expected and $actualObject->actualAttributeName are not equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeEquals(array $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if the two arrays $expected and $actualObject->actualAttributeName are not equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(array $expected, string $actualAttributeName, object $actualObject)Reports an error if the two arrays $expected and $actualObject->actualAttributeName are equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(array $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if the two arrays $expected and $actualObject->actualAttributeName are equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeEquals(float $expected, string $actualAttributeName, object $actualObject, '', float $delta = 0)Reports an error if the two floats $expected and $actualObject->actualAttributeName are not within $delta of each other. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeEquals(float $expected, string $actualAttributeName, object $actualObject, string $message, float $delta = 0)Reports an error identified by $message if the two floats $expected and $actualObject->actualAttributeName are not within $delta of each other. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(float $expected, string $actualAttributeName, object $actualObject, '', float $delta = 0)Reports an error if the two floats $expected and $actualObject->actualAttributeName are within $delta of each other. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(float $expected, string $actualAttributeName, object $actualObject, string $message, float $delta = 0)Reports an error identified by $message if the two floats $expected and $actualObject->actualAttributeName are within $delta of each other. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeEquals(string $expected, string $actualAttributeName, object $actualObject)Reports an error if the two strings $expected and $actualObject->actualAttributeName are not equal. The error is reported as the delta between the two strings. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeEquals(string $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if the two strings $expected and $actualObject->actualAttributeName are not equal. The error is reported as the delta between the two strings. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(string $expected, string $actualAttributeName, object $actualObject)Reports an error if the two strings $expected and $actualObject->actualAttributeName are equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(string $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if the two strings $expected and $actualObject->actualAttributeName are equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeEquals(mixed $expected, string $actualAttributeName, object $actualObject)Reports an error if the two variables $expected and $actualObject->actualAttributeName are not equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeEquals(mixed $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if the two variables $expected and $actualObject->actualAttributeName are not equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(mixed $expected, string $actualAttributeName, object $actualObject)Reports an error if the two variables $expected and $actualObject->actualAttributeName are equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotEquals(mixed $expected, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if the two variables $expected and $actualObject->actualAttributeName are equal. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertContains(mixed $needle, array $haystack)Reports an error if $needle is not an element of $haystack.
void assertContains(mixed $needle, array $haystack, string $message)Reports an error identified by $message if $needle is not an element of $haystack.
void assertNotContains(mixed $needle, array $haystack)Reports an error if $needle is an element of $haystack.
void assertNotContains(mixed $needle, array $haystack, string $message)Reports an error identified by $message if $needle is an element of $haystack.
void assertContains(mixed $needle, Iterator $haystack)Reports an error if $needle is not an element of $haystack.
void assertContains(mixed $needle, Iterator $haystack, string $message)Reports an error identified by $message if $needle is not an element of $haystack.
void assertNotContains(mixed $needle, Iterator $haystack)Reports an error if $needle is an element of $haystack.
void assertNotContains(mixed $needle, Iterator $haystack, string $message)Reports an error identified by $message if $needle is an element of $haystack.
void assertContains(string $needle, string $haystack)Reports an error if $needle is not a substring of $haystack.
void assertContains(string $needle, string $haystack, string $message)Reports an error identified by $message if $needle is not a substring of $haystack.
void assertNotContains(string $needle, string $haystack)Reports an error if $needle is a substring of $haystack.
void assertNotContains(string $needle, string $haystack, string $message)Reports an error identified by $message if $needle is a substring of $haystack.
void assertAttributeContains(mixed $needle, string $actualAttributeName, object $actualObject)Reports an error if $needle is not an element of $actualObject->actualAttributeName which can be an array, a string, or an object that implements the Iterator interface. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeContains(mixed $needle, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if $needle is not an element of $actualObject->actualAttributeName which can be an array, a string, or an object that implements the Iterator interface. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotContains(mixed $needle, string $actualAttributeName, object $actualObject)Reports an error if $needle is an element of $actualObject->actualAttributeName which can be an array, a string, or an object that implements the Iterator interface. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertAttributeNotContains(mixed $needle, string $actualAttributeName, object $actualObject, string $message)Reports an error identified by $message if $needle is an element of $actualObject->actualAttributeName which can be an array, a string, or an object that implements the Iterator interface. The visibility of the $actualObject->actualAttributeName attribute may be public, protected, or private.
void assertRegExp(string $pattern, string $string)Reports an error if $string does not match the regular expression $pattern.
void assertRegExp(string $pattern, string $string, string $message)Reports an error identified by $message if $string does not match the regular expression $pattern.
void assertNotRegExp(string $pattern, string $string)Reports an error if $string matches the regular expression $pattern.
void assertNotRegExp(string $pattern, string $string, string $message)Reports an error identified by $message if $string matches the regular expression $pattern.
void assertType(string $expected, mixed $actual)Reports an error if the variable $actual is not of type $expected.
void assertType(string $expected, mixed $actual, string $message)Reports an error identified by $message if the variable $actual is not of type $expected.
void assertNotType(string $expected, mixed $actual)Reports an error if the variable $actual is of type $expected.
void assertNotType(string $expected, mixed $actual, string $message)Reports an error identified by $message if the variable $actual is of type $expected.
void assertFileExists(string $filename)Reports an error if the file specified by $filename does not exist.
void assertFileExists(string $filename, string $message)Reports an error identified by $message if the file specified by $filename does not exist.
void assertFileNotExists(string $filename)Reports an error if the file specified by $filename exists.
void assertFileNotExists(string $filename, string $message)Reports an error identified by $message if the file specified by $filename exists.
void assertObjectHasAttribute(string $attributeName, object $object)Reports an error if $object->attributeName does not exist.
void assertObjectHasAttribute(string $attributeName, object $object, string $message)Reports an error identified by $message if $object->attributeName does not exist.
void assertObjectNotHasAttribute(string $attributeName, object $object)Reports an error if $object->attributeName exists.
void assertObjectNotHasAttribute(string $attributeName, object $object, string $message)Reports an error identified by $message if $object->attributeName exists.


More complex assertions can be formulated using the PHPUnit_Framework_Constraint classes. They can be evaluated using the assertThat() method as shown in Example 21.3.

Example 21.3: Using assertThat() with constraint objects

<?php
require_once 'PHPUnit/Framework.php';
 
class ConstraintTest extends PHPUnit_Framework_TestCase
{
    public function testNotEquals()
    {
        $constraint = $this->logicalNot(
          $this->equalTo('foo')
        );
 
        $this->assertThat('foo', $constraint);
    }
}
?>
<userinput>phpunit ConstraintTest</userinput>
PHPUnit 3.1.0 by Sebastian Bergmann.

F

Time: 00:00

There was 1 failure:

1) testNotEquals(ConstraintTest)
Failed asserting that <string:foo> is not equal to <string:foo>.
/home/sb/ConstraintTest.php:12

FAILURES!
Tests: 1, Failures: 1.


Table 21.2 shows the available PHPUnit_Framework_Constraint implementations.

Table21.2.Constraints

ConstraintMeaning
PHPUnit_Framework_Constraint_IsAnything anything()Constraint that accepts any input value.
PHPUnit_Framework_Constraint_ArrayHasKey arrayHasKey(mixed $key)Constraint that asserts that the array it is evaluated for has a given key.
PHPUnit_Framework_Constraint_TraversableContains contains(mixed $value)Constraint that asserts that the array or object that implements the Iterator interface it is evaluated for contains a given value.
PHPUnit_Framework_Constraint_IsEqual equalTo(mixed $value)Constraint that checks if one value is equal to another.
PHPUnit_Framework_Constraint_FileExists fileExists()Constraint that checks if the file(name) that it is evaluated for exists.
PHPUnit_Framework_Constraint_GreaterThan greaterThan(mixed $value)Constraint that asserts that the value it is evaluated for is greater than a given value.
PHPUnit_Framework_Constraint_ObjectHasAttribute hasProperty(string $property)Constraint that asserts that the object it is evaluated for has a given attribute.
PHPUnit_Framework_Constraint_IsIdentical identicalTo(mixed $value)Constraint that asserts that one value is identical to another.
PHPUnit_Framework_Constraint_IsInstanceOf isInstanceOf(string $className)Constraint that asserts that the object it is evaluated for is an instance of a given class.
PHPUnit_Framework_Constraint_IsType isType(string $type)Constraint that asserts that the value it is evaluated for is of a specified type.
PHPUnit_Framework_Constraint_LessThan lessThan(mixed $value)Constraint that asserts that the value it is evaluated for is less than a given value.
logicalAnd()Logical AND.
logicalNot(PHPUnit_Framework_Constraint $constraint)Logical NOT.
logicalOr()Logical OR.
logicalXor()Logical XOR.
PHPUnit_Framework_Constraint_PCREMatch matchesRegularExpression(string $pattern)Constraint that asserts that the string it is evaluated for matches a regular expression.
PHPUnit_Framework_Constraint_StringContains stringContains(string $string, bool $case)Constraint that asserts that the string it is evaluated for contains a given string.


You may find that you need other assertions than these to compare objects specific to your project. Create your own Assert class to contain these assertions to simplify your tests.

Failing assertions all call a single bottleneck method, fail(string $message), which throws an PHPUnit_Framework_AssertionFailedError. There is also a variant which takes no parameters. Call fail() explicitly when your test encounters an error. The test for an expected exception is an example. Table 21.3 lists the bottlenext methods in PHPUnit.

Table21.3.Bottleneck Methods

MethodMeaning
void fail()Reports an error.
void fail(string $message)Reports an error identified by $message.


markTestIncomplete() and markTestSkipped() are convenience methods for marking a test as being incomplete or skipped.

Table21.4.Marking a test as being incomplete or skipped

MethodMeaning
void markTestIncomplete(string $message)Marks the current test as being incomplete, $message is optional.
void markTestSkipped(string $message)Marks the current test as being skipped, $message is optional.


Although unit tests are about testing the public interface of a class, you may sometimes want to test the values of non-public properties. The getNonPublicProperty() method enables you to do this and returns the value of a given non-public property from a given object.

Table21.5.Accessing non-public properties

MethodMeaning
Mixed getNonPublicProperty($object, $propertyName)Returns the value of the non-public property $propertyName of the given object.


PHPUnit_Framework_Test

PHPUnit_Framework_Test is the generic interface used by all objects that can act as tests. Implementors may represent one or more tests. The two methods are shown in Table 21.6.

Table21.6.Implementor Methods

MethodMeaning
int count()Return the number of tests.
void run(PHPUnit_Framework_TestResult $result)Run the tests and report the results on $result.


PHPUnit_Framework_TestCase and PHPUnit_Framework_TestSuite are the two most prominent implementors of PHPUnit_Framework_Test. You can implement PHPUnit_Framework_Test yourself. The interface is kept small intentionally so it will be easy to implement.

PHPUnit_Framework_TestCase

Your test-case classes will inherit from PHPUnit_Framework_TestCase. Most of the time, you will run tests from automatically created test suites. In this case, each of your tests should be represented by a method named test* (by convention).

PHPUnit_Framework_TestCase implements PHPUnit_Framework_Test::count() so that it always returns 1. The implementation of PHPUnit_Framework_Test::run(PHPUnit_Framework_TestResult $result) in this class runs setUp(), runs the test method, and then runs tearDown(), reporting any exceptions to the PHPUnit_Framework_TestResult.

Table 21.7 shows the methods provided by PHPUnit_Framework_TestCase.

Table21.7.TestCase

MethodMeaning
__construct()Creates a test case.
__construct(string $name)Creates a named test case. Names are used to print the test case and often as the name of the test method to be run by reflection.
string getName()Return the name of the test case.
void setName($name)Set the name of the test case.
PHPUnit_Framework_TestResult run(PHPUnit_Framework_TestResult $result)Convenience method to run the test case and report it in $result.
void runTest()Override with a testing method if you do not want the testing method to be invoked by reflection.
object getMock($className, [array $methods, [array $arguments, [string $mockClassName]]])Returns a mock object (see Chapter 10) for the specified $className. By default, all methods of the given class are mocked. When the second (optional) parameter is provided, only the methods whose names are in the array are mocked. The third (optional) parameter may hold a parameter array that is passed to the mock object's constructor. The fourth (optional) parameter can be used to specify a class name for the mock object.


There are two template methods -- setUp() and tearDown() -- you can override to create and dispose of the objects against which you are going to test. Table 21.8 shows these methods. A third template method, sharedAssertions(), allows to define assertions that should be performed by all tests of a test case.

Table21.8.Template Methods

MethodMeaning
void setUp()Override to create objects against which to test. Each test that runs will be run in its own test case, and setUp() will be called separately for each one.
void sharedAssertions()Override to perform assertions that are shared by all tests of a test case. This method is called before the execution of a test ends and before tearDown() is called.
void tearDown()Override to dispose of objects no longer needed once the test has finished. In general, you only need to explicitly dispose of external resources (files or sockets, for example) in tearDown().


PHPUnit_Framework_TestSuite

A PHPUnit_Framework_TestSuite is a composite of PHPUnit_Framework_Tests. At its simplest, it contains a bunch of test cases, all of which are run when the suite is run. Since it is a composite, however, a suite can contain suites which can contain suites and so on, making it easy to combine tests from various sources and run them together.

In addition to the PHPUnit_Framework_Test methods -- run(PHPUnit_Framework_TestResult $result) and count() -- PHPUnit_Framework_TestSuite provides methods to create named or unnamed instances. Table 21.9 shows the methods to create PHPUnit_Framework_TestSuite instances.

Table21.9.Creating named or unnamed instances

MethodMeaning
__construct()Return an empty test suite.
__construct(string $theClass)Return a test suite containing an instance of the class named $theClass for each method in the class named test*. If no class of name $theClass exists an empty test suite named $theClass is returned.
__construct(string $theClass, string $name)Return a test suite named $name containing an instance of the class named $theClass for each method in the class named test*.
__construct(ReflectionClass $theClass)Return a test suite containing an instance of the class represented by $theClass for each method in the class named test*.
__construct(ReflectionClass $theClass, $name)Return a test suite named $name containing an instance of the class represented by $theClass for each method in the class named test*.
string getName()Return the name of the test suite.
void setName(string $name)Set the name of the test suite.


PHPUnit_Framework_TestSuite also provides methods for adding and retrieving PHPUnit_Framework_Tests, as shown in Table 21.10.

Table21.10.Adding and retrieving tests

MethodMeaning
void addTestSuite(PHPUnit_Framework_TestSuite $suite)Add another test suite to the test suite.
void addTestSuite(string $theClass)Add a test suite containing an instance of the class named $theClass for each method in the class named test* to the test suite.
void addTestSuite(ReflectionClass $theClass)Add a test suite containing an instance of the class represented by $theClass for each method in the class named test* to the test suite.
void addTest(PHPUnit_Framework_Test $test)Add $test to the suite.
void addTestFile(string $filename)Add the tests that are defined in the class(es) of a given sourcefile to the suite.
void addTestFiles(array $filenames)Add the tests that are defined in the classes of the given sourcefiles to the suite.
int testCount()Return the number of tests directly (not recursively) in this suite.
PHPUnit_Framework_Test[] tests()Return the tests directly in this suite.
PHPUnit_Framework_Test testAt(int $index)Return the test at the $index.


Example 21.4 shows how to create and run a test suite.

Example 21.4: Creating and running a test suite

<?php
require_once 'PHPUnit/Framework.php';
 
require_once 'ArrayTest.php';
 
// Create a test suite that contains the tests
// from the ArrayTest class.
$suite = new PHPUnit_Framework_TestSuite('ArrayTest');
 
// Run the tests.
$suite->run();
?>


Chapter 6 shows how to use the PHPUnit_Framework_TestSuite class to organize test suites by hierarchically composing test cases.

The PHPUnit_Framework_TestSuite class provides two template methods -- setUp() and tearDown() -- that are called before and after the tests of a test suite are run, respectively.

Table21.11.Template Methods

MethodMeaning
void setUp()Called before the first test of the test suite is run.
void tearDown()Called after the last test of the test suite has been run.


PHPUnit_Framework_TestResult

While you are running all these tests, you need somewhere to store all the results: how many tests ran, which failed, and how long they took. PHPUnit_Framework_TestResult collects these results. A single PHPUnit_Framework_TestResult is passed around the whole tree of tests; when a test runs or fails, the fact is noted in the PHPUnit_Framework_TestResult. At the end of the run, PHPUnit_Framework_TestResult contains a summary of all the tests.

PHPUnit_Framework_TestResult is also a subject than can be observed by other objects wanting to report test progress. For example, a graphical test runner might observe the PHPUnit_Framework_TestResult and update a progress bar every time a test starts.

Table 21.12 summarizes the API of PHPUnit_Framework_TestResult.

Table21.12.TestResult

MethodMeaning
void addError(PHPUnit_Framework_Test $test, Exception $e)Record that running $test caused $e to be thrown unexpectedly.
void addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e)Record that running $test caused $e to be thrown unexpectedly.
PHPUnit_Framework_TestFailure[] errors()Return the errors recorded.
PHPUnit_Framework_TestFailure[] failures()Return the failures recorded.
PHPUnit_Framework_TestFailure[] notImplemented()Return the incomplete test cases recorded.
int errorCount()Return the number of errors.
int failureCount()Return the number of failures.
int notImplementedCount()Return the number of incomplete test cases.
int count()Return the total number of test cases run.
boolean wasSuccessfull()Return whether or not all tests ran successfully.
boolean allCompletlyImplemented()Return whether or not all tests were completely implemented.
void collectCodeCoverageInformation(bool $flag)Enables or disables the collection of Code Coverage information.
array getCodeCoverageInformation()Return the code coverage information collected.


If you want to register as an observer of a PHPUnit_Framework_TestResult, you need to implement PHPUnit_Framework_TestListener. To register, call addListener(), as shown in Table 21.13.

Table21.13.TestResult and TestListener

MethodMeaning
void addListener(PHPUnit_Framework_TestListener $listener)Register $listener to receive updates as results are recorded in the test result.
void removeListener(PHPUnit_Framework_TestListener $listener)Unregister $listener from receiving updates.


Table 21.14 shows the methods that test listeners implement; also see Example 22.3.

Table21.14.TestListener Callbacks

MethodMeaning
void addError(PHPUnit_Framework_Test $test, Exception $e)$test has thrown $e.
void addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e)$test has failed an assertion, throwing a kind of PHPUnit_Framework_AssertionFailedError.
void addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e)$test is an incomplete test.
void addSkippedTest(PHPUnit_Framework_Test $test, Exception $e)$test is a test that has been skipped.
void startTestSuite(PHPUnit_Framework_TestSuite $suite)$suite is about to be run.
void endTestSuite(PHPUnit_Framework_TestSuite $suite)$suite has finished running.
void startTest(PHPUnit_Framework_Test $test)$test is about to be run.
void endTest(PHPUnit_Framework_Test $test)$test has finished running.


Package Structure

Many of the classes mentioned so far in this book come from PHPUnit/Framework. Here are all the packages in PHPUnit:

  • PHPUnit/Framework

    The basic classes in PHPUnit.

  • PHPUnit/Extensions

    Extensions to the PHPUnit framework.

  • PHPUnit/Runner

    Abstract support for running tests.

  • PHPUnit/TextUI

    The text-based test runner.

  • PHPUnit/Util

    Utility classes used by the other packages.