Prev | Next |
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.
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 22.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
.
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 22.1).
Example 22.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 22.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 22.2, using
assertions with messages:
phpunit MessageTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testMessage(MessageTest)
This is a custom message.
Failed asserting that <boolean:false> is true.
/home/sb/MessageTest.php:8
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
Below are all the varieties of assertions.
assertArrayHasKey(mixed $key, array $array[, string $message = ''])
Reports an error identified by $message
if $array
does not have the $key
.
assertArrayNotHasKey()
is the inverse of this assertion and takes the same arguments.
Example 22.3: Usage of assertArrayHasKey()
<?php
class ArrayHasKeyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertArrayHasKey('foo', array('bar' => 'baz'));
}
}
?>
phpunit ArrayHasKeyTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(ArrayHasKeyTest)
Failed asserting that an array has the key <string:foo>.
/home/sb/ArrayHasKeyTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertClassHasAttribute(string $attributeName, string $className[, string $message = ''])
Reports an error identified by $message
if $className::attributeName
does not exist.
assertClassNotHasAttribute()
is the inverse of this assertion and takes the same arguments.
Example 22.4: Usage of assertClassHasAttribute()
<?php
class ClassHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasAttributeTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(ClassHasAttributeTest)
Failed asserting that class "stdClass" has attribute "foo".
/home/sb/ClassHasAttributeTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertClassHasStaticAttribute(string $attributeName, string $className[, string $message = ''])
Reports an error identified by $message
if $className::attributeName
does not exist.
assertClassNotHasStaticAttribute()
is the inverse of this assertion and takes the same arguments.
Example 22.5: Usage of assertClassHasStaticAttribute()
<?php
class ClassHasStaticAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasStaticAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasStaticAttributeTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(ClassHasStaticAttributeTest)
Failed asserting that class "stdClass" has static attribute "foo".
/home/sb/ClassHasStaticAttributeTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertContains(mixed $needle, Iterator|array $haystack[, string $message = ''])
Reports an error identified by $message
if $needle
is not an element of $haystack
.
assertNotContains()
is the inverse of this assertion and takes the same arguments.
assertAttributeContains()
and assertAttributeNotContains()
are convenience wrappers that use a public
, protected
, or private
attribute of a class or object as the haystack.
Example 22.6: Usage of assertContains()
<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains(4, array(1, 2, 3));
}
}
?>
phpunit ContainsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(ContainsTest)
Failed asserting that an array contains <integer:4>.
/home/sb/ContainsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertContains(string $needle, string $haystack[, string $message = ''])
Reports an error identified by $message
if $needle
is not a substring of $haystack
.
Example 22.7: Usage of assertContains()
<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains('baz', 'foobar');
}
}
?>
phpunit ContainsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(ContainsTest)
Failed asserting that <string:foobar> contains "baz".
/home/sb/ContainsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertContainsOnly(string $type, Iterator|array $haystack[, boolean $isNativeType = NULL, string $message = ''])
Reports an error identified by $message
if $haystack
does not contain only variables of type $type
.
$isNativeType
is a flag used to indicate whether $type
is a native PHP type or not.
assertNotContainsOnly()
is the inverse of this assertion and takes the same arguments.
assertAttributeContainsOnly()
and assertAttributeNotContainsOnly()
are convenience wrappers that use a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.8: Usage of assertContainsOnly()
<?php
class ContainsOnlyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContainsOnly('string', array('1', '2', 3));
}
}
?>
phpunit ContainsOnlyTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(ContainsOnlyTest)
Failed asserting that
Array
(
[0] => 1
[1] => 2
[2] => 3
)
contains only values of type "string".
/home/sb/ContainsOnlyTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertEqualXMLStructure(DOMNode $expectedNode, DOMNode $actualNode[, boolean $checkAttributes = FALSE, string $message = ''])
XXX
assertEquals(mixed $expected, mixed $actual[, string $message = ''])
Reports an error identified by $message
if the two variables $expected
and $actual
are not equal.
assertNotEquals()
is the inverse of this assertion and takes the same arguments.
assertAttributeEquals()
and assertAttributeNotEquals()
are convenience wrappers that use a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.10: Usage of assertEquals()
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertEquals(1, 0);
}
public function testFailure2()
{
$this->assertEquals('bar', 'baz');
}
public function testFailure3()
{
$this->assertEquals("foo\nbar\nbaz\n", "foo\nbah\nbaz\n");
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
FFF
Time: 0 seconds
There were 3 failures:
1) testFailure(EqualsTest)
Failed asserting that <integer:0> matches expected value <integer:1>.
/home/sb/EqualsTest.php:11
2) testFailure2(EqualsTest)
Failed asserting that two strings are equal.
expected string <bar>
difference < x>
got string <baz>
/home/sb/EqualsTest.php:16
3) testFailure3(EqualsTest)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,3 +1,3 @@
foo
-bar
+bah
baz
/home/sb/EqualsTest.php:21
FAILURES!
Tests: 3, Assertions: 3, Failures: 3.
More specialized comparisons are used for specific argument types for $expected
and $actual
, see below.
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.
Please read about comparing floating-point numbers to understand why $delta
is neccessary.
Example 22.11: Usage of assertEquals() with floats
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testSuccess()
{
$this->assertEquals(1.0, 1.1, '', 0.2);
}
public function testFailure()
{
$this->assertEquals(1.0, 1.1);
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
.F
Time: 0 seconds
There was 1 failure:
1) testFailure(EqualsTest)
Failed asserting that <double:1.1> matches expected value <double:1>.
/home/sb/EqualsTest.php:11
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
assertEquals(DOMDocument $expected, DOMDocument $actual[, string $message = ''])
Reports an error identified by $message
if the XML documents represented by the two DOMDocument objects $expected
and $actual
are not equal.
Example 22.12: Usage of assertEquals() with DOMDocument objects
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$expected = new DOMDocument;
$expected->loadXML('<foo><bar/></foo>');
$actual = new DOMDocument;
$actual->loadXML('<bar><foo/></bar>');
$this->assertEquals($expected, $actual);
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(EqualsTest)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
-<foo>
- <bar/>
-</foo>
+<bar>
+ <foo/>
+</bar>
/home/sb/EqualsTest.php:12
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertEquals(object $expected, object $actual[, string $message = ''])
Reports an error identified by $message
if the two objects $expected
and $actual
do not have equal attribute values.
Example 22.13: Usage of assertEquals() with objects
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$expected = new stdClass;
$expected->foo = 'foo';
$expected->bar = 'bar';
$actual = new stdClass;
$actual->foo = 'bar';
$actual->baz = 'bar';
$this->assertEquals($expected, $actual);
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(EqualsTest)
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ -1,5 +1,5 @@
stdClass Object
(
- [foo] => foo
- [bar] => bar
+ [foo] => bar
+ [baz] => bar
)
/home/sb/EqualsTest.php:14
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertEquals(array $expected, array $actual[, string $message = ''])
Reports an error identified by $message
if the two arrays $expected
and $actual
are not equal.
Example 22.14: Usage of assertEquals() with arrays
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertEquals(array('a', 'b', 'c'), array('a', 'c', 'd'));
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(EqualsTest)
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ -1,6 +1,6 @@
Array
(
[0] => a
- [1] => b
- [2] => c
+ [1] => c
+ [2] => d
)
/home/sb/EqualsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertFalse(bool $condition[, string $message = ''])
Reports an error identified by $message
if $condition
is TRUE
.
Example 22.15: Usage of assertFalse()
<?php
class FalseTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFalse(TRUE);
}
}
?>
phpunit FalseTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(FalseTest)
Failed asserting that <boolean:true> is false.
/home/sb/FalseTest.php:11
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertFileEquals(string $expected, string $actual[, string $message = ''])
Reports an error identified by $message
if the file specified by $expected
does not have the same contents as the file specified by $actual
.
assertFileNotEquals()
is the inverse of this assertion and takes the same arguments.
Example 22.16: Usage of assertFileEquals()
<?php
class FileEqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileEquals('/home/sb/expected', '/home/sb/actual');
}
}
?>
phpunit FileEqualsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(FileEqualsTest)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,2 +1,2 @@
-expected
+actual
/home/sb/FileEqualsTest.php:6
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
assertFileExists(string $filename[, string $message = ''])
Reports an error identified by $message
if the file specified by $filename
does not exist.
assertFileNotExists()
is the inverse of this assertion and takes the same arguments.
Example 22.17: Usage of assertFileExists()
<?php
class FileExistsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileExists('/path/to/file');
}
}
?>
phpunit FileExistsTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(FileExistsTest)
Failed asserting that file "/path/to/file" exists.
/home/sb/FileExistsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertGreaterThan(mixed $expected, mixed $actual[, string $message = ''])
Reports an error identified by $message
if the value of $actual
is not greater than the value of $expected
.
assertAttributeGreaterThan()
is a convenience wrapper that uses a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.18: Usage of assertGreaterThan()
<?php
class GreaterThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThan(2, 1);
}
}
?>
phpunit GreaterThanTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(GreaterThanTest)
Failed asserting that <integer:1> is greater than <integer:2>.
/home/sb/GreaterThanTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertGreaterThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])
Reports an error identified by $message
if the value of $actual
is not greater than or equal to the value of $expected
.
assertAttributeGreaterThanOrEqual()
is a convenience wrapper that uses a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.19: Usage of assertGreaterThanOrEqual()
<?php
class GreatThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThanOrEqual(2, 1);
}
}
?>
phpunit GreaterThanOrEqualTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(GreatThanOrEqualTest)
Failed asserting that <integer:1> is equal to <integer:2> or is greater than <integer:2>.
/home/sb/GreaterThanOrEqualTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertLessThan(mixed $expected, mixed $actual[, string $message = ''])
Reports an error identified by $message
if the value of $actual
is not less than the value of $expected
.
assertAttributeLessThan()
is a convenience wrapper that uses a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.20: Usage of assertLessThan()
<?php
class LessThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThan(1, 2);
}
}
?>
phpunit LessThanTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(LessThanTest)
Failed asserting that <integer:2> is less than <integer:1>.
/home/sb/LessThanTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertLessThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])
Reports an error identified by $message
if the value of $actual
is not less than or equal to the value of $expected
.
assertAttributeLessThanOrEqual()
is a convenience wrapper that uses a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.21: Usage of assertLessThanOrEqual()
<?php
class LessThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThanOrEqual(1, 2);
}
}
?>
phpunit LessThanOrEqualTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(LessThanOrEqualTest)
Failed asserting that <integer:2> is equal to <integer:1> or is less than <integer:1>.
/home/sb/LessThanOrEqualTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertNotNull(mixed $variable[, string $message = ''])
Reports an error identified by $message
if $variable
is NULL
.
assertNull()
is the inverse of this assertion and takes the same arguments.
Example 22.22: Usage of assertNotNull()
<?php
class NotNullTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertNotNull(NULL);
}
}
?>
phpunit NotNullTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(NotNullTest)
Failed asserting that <null> is not null.
/home/sb/NotNullTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertObjectHasAttribute(string $attributeName, object $object[, string $message = ''])
Reports an error identified by $message
if $object->attributeName
does not exist.
assertObjectNotHasAttribute()
is the inverse of this assertion and takes the same arguments.
Example 22.23: Usage of assertObjectHasAttribute()
<?php
class ObjectHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertObjectHasAttribute('foo', new stdClass);
}
}
?>
phpunit ObjectHasAttributeTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(ObjectHasAttributeTest)
Failed asserting that object of class "stdClass" has attribute "foo".
/home/sb/ObjectHasAttributeTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertRegExp(string $pattern, string $string[, string $message = ''])
Reports an error identified by $message
if $string
does not match the regular expression $pattern
.
assertNotRegExp()
is the inverse of this assertion and takes the same arguments.
Example 22.24: Usage of assertRegExp()
<?php
class RegExpTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertRegExp('/foo/', 'bar');
}
}
?>
phpunit RegExpTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(RegExpTest)
Failed asserting that <string:bar> matches PCRE pattern "/foo/".
/home/sb/RegExpTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
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.
assertNotSame()
is the inverse of this assertion and takes the same arguments.
assertAttributeSame()
and assertAttributeNotSame()
are convenience wrappers that use a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.25: Usage of assertSame()
<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame('2204', 2204);
}
}
?>
phpunit SameTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(SameTest)
<integer:2204> does not match expected type "string".
/home/sb/SameTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
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.
Example 22.26: Usage of assertSame() with objects
<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame(new stdClass, new stdClass);
}
}
?>
phpunit SameTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(SameTest)
Failed asserting that two variables reference the same object.
/home/sb/SameTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertSelectCount(array $selector, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])
XXX
assertSelectEquals(array $selector, string $content, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])
XXX
assertSelectRegExp(array $selector, string $pattern, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])
XXX
assertStringEndsWith(string $suffix, string $string[, string $message = ''])
Reports an error identified by $message
if the $string
does not end with $suffix
.
assertStringEndsNotWith()
is the inverse of this assertion and takes the same arguments.
Example 22.30: Usage of assertStringEndsWith()
<?php
class StringEndsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEndsWith('suffix', 'foo');
}
}
?>
phpunit StringEndsWithTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(StringEndsWithTest)
Failed asserting that <string:foo> ends with "suffix".
/home/sb/StringEndsWithTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertStringEqualsFile(string $expectedFile, string $actualString[, string $message = ''])
Reports an error identified by $message
if the file specified by $expectedFile
does not have $actualString
as its contents.
assertStringNotEqualsFile()
is the inverse of this assertion and takes the same arguments.
Example 22.31: Usage of assertStringEqualsFile()
<?php
class StringEqualsFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEqualsFile('/home/sb/expected', 'actual');
}
}
?>
phpunit StringEqualsFileTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(StringEqualsFileTest)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,2 +1 @@
-expected
-
+actual
\ No newline at end of file
/home/sb/StringEqualsFileTest.php:6
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
assertStringStartsWith(string $prefix, string $string[, string $message = ''])
Reports an error identified by $message
if the $string
does not start with $prefix
.
assertStringStartsNotWith()
is the inverse of this assertion and takes the same arguments.
Example 22.32: Usage of assertStringStartsWith()
<?php
class StringStartsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringStartsWith('prefix', 'foo');
}
}
?>
phpunit StringStartsWithTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(StringStartsWithTest)
Failed asserting that <string:foo> starts with "prefix".
/home/sb/StringStartsWithTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertTag(array $matcher, string $actual[, string $message = '', boolean $isHtml = TRUE])
Reports an error identified by $message
if $actual
is not matched by the $matcher
.
$matcher
is an associative array that specifies the match criteria for the assertion:
id
: The node with the given id
attribute must match the corresponsing value.tags
: The node type must match the corresponding value.attributes
: The node's attributes must match the corresponsing values in the $attributes
associative array.content
: The text content must match the given value.parent
: The node's parent must match the $parent
associative array.child
: At least one of the node's immediate children must meet the criteria described by the $child
associative array.ancestor
: At least one of the node's ancestors must meet the criteria described by the $ancestor
associative array.descendant
: At least one of the node's descendants must meet the criteria described by the $descendant
associative array.children
: Associative array for counting children of a node.
count
: The number of matching children must be equal to this number.less_than
: The number of matching children must be less than this number.greater_than
: The number of matching children must be greater than this number.only
: Another associative array consisting of the keys to use to match on the children, and only matching children will be counted.assertNotTag()
is the inverse of this assertion and takes the same arguments.
Example 22.33: Usage of assertTag()
<?php
// Matcher that asserts that there is an element with an id="my_id".
$matcher = array('id' => 'my_id');
// Matcher that asserts that there is a "span" tag.
$matcher = array('tag' => 'span');
// Matcher that asserts that there is a "span" tag with the content
// "Hello World".
$matcher = array('tag' => 'span', 'content' => 'Hello World');
// Matcher that asserts that there is a "span" tag with content matching the
// regular expression pattern.
$matcher = array('tag' => 'span', 'content' => '/Try P(HP|ython)/');
// Matcher that asserts that there is a "span" with an "list" class attribute.
$matcher = array(
'tag' => 'span',
'attributes' => array('class' => 'list')
);
// Matcher that asserts that there is a "span" inside of a "div".
$matcher = array(
'tag' => 'span',
'parent' => array('tag' => 'div')
);
// Matcher that asserts that there is a "span" somewhere inside a "table".
$matcher = array(
'tag' => 'span',
'ancestor' => array('tag' => 'table')
);
// Matcher that asserts that there is a "span" with at least one "em" child.
$matcher = array(
'tag' => 'span',
'child' => array('tag' => 'em')
);
// Matcher that asserts that there is a "span" containing a (possibly nested)
// "strong" tag.
$matcher = array(
'tag' => 'span',
'descendant' => array('tag' => 'strong')
);
// Matcher that asserts that there is a "span" containing 5-10 "em" tags as
// immediate children.
$matcher = array(
'tag' => 'span',
'children' => array(
'less_than' => 11,
'greater_than' => 4,
'only' => array('tag' => 'em')
)
);
// Matcher that asserts that there is a "div", with an "ul" ancestor and a "li"
// parent (with class="enum"), and containing a "span" descendant that contains
// an element with id="my_test" and the text "Hello World".
$matcher = array(
'tag' => 'div',
'ancestor' => array('tag' => 'ul'),
'parent' => array(
'tag' => 'li',
'attributes' => array('class' => 'enum')
),
'descendant' => array(
'tag' => 'span',
'child' => array(
'id' => 'my_test',
'content' => 'Hello World'
)
)
);
// Use assertTag() to apply a $matcher to a piece of $html.
$this->assertTag($matcher, $html);
// Use assertTag() to apply a $matcher to a piece of $xml.
$this->assertTag($matcher, $xml, '', FALSE);
?>
More complex assertions can be formulated using the
PHPUnit_Framework_Constraint
classes. They can be
evaluated using the assertThat()
method.
Example 22.34 shows how the
logicalNot()
and equalTo()
constraints can be used to express the same assertion as
assertNotEquals()
.
assertThat(mixed $value, PHPUnit_Framework_Constraint $constraint[, $message = ''])
Reports an error identified by $message
if the $value
does not match the $constraint
.
Example 22.34: Usage of assertThat()
<?php
class BiscuitTest extends PHPUnit_Framework_TestCase
{
public function testEquals()
{
$theBiscuit = new Biscuit('Ginger');
$myBiscuit = new Biscuit('Ginger');
$this->assertThat(
$theBiscuit,
$this->logicalNot(
$this->equalTo($myBiscuit)
)
);
}
}
?>
Table 22.1 shows the
available PHPUnit_Framework_Constraint
classes.
Table 22.1. Constraints
Constraint | Meaning |
---|---|
PHPUnit_Framework_Constraint_Attribute attribute(PHPUnit_Framework_Constraint $constraint, $attributeName) | Constraint that applies another constraint to an attribute of a class or an object. |
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($value, $delta = 0, $maxDepth = 10) | Constraint that checks if one value is equal to another. |
PHPUnit_Framework_Constraint_Attribute attributeEqualTo($attributeName, $value, $delta = 0, $maxDepth = 10) | Constraint that checks if a value is equal to an attribute of a class or of an object. |
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_Or greaterThanOrEqual(mixed $value) | Constraint that asserts that the value it is evaluated for is greater than or equal to a given value. |
PHPUnit_Framework_Constraint_ClassHasAttribute classHasAttribute(string $attributeName) | Constraint that asserts that the class it is evaluated for has a given attribute. |
PHPUnit_Framework_Constraint_ClassHasStaticAttribute classHasStaticAttribute(string $attributeName) | Constraint that asserts that the class it is evaluated for has a given static attribute. |
PHPUnit_Framework_Constraint_ObjectHasAttribute hasAttribute(string $attributeName) | 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_IsFalse isFalse() | Constraint that asserts that the value it is evaluated is FALSE . |
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_IsNull isNull() | Constraint that asserts that the value it is evaluated is NULL . |
PHPUnit_Framework_Constraint_IsTrue isTrue() | Constraint that asserts that the value it is evaluated is TRUE . |
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 smaller than a given value. |
PHPUnit_Framework_Constraint_Or lessThanOrEqual(mixed $value) | Constraint that asserts that the value it is evaluated for is smaller than or equal to 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. |
PHPUnit_Framework_Constraint_StringEndsWith stringEndsWith(string $suffix) | Constraint that asserts that the string it is evaluated for ends with a given suffix. |
PHPUnit_Framework_Constraint_StringStartsWith stringStartsWith(string $prefix) | Constraint that asserts that the string it is evaluated for starts with a given prefix. |
assertTrue(bool $condition[, string $message = ''])
Reports an error identified by $message
if $condition
is FALSE
.
Example 22.35: Usage of assertTrue()
<?php
class TrueTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertTrue(FALSE);
}
}
?>
phpunit TrueTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(TrueTest)
Failed asserting that <boolean:false> is true.
/home/sb/TrueTest.php:11
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertType(string $expected, mixed $actual[, string $message = ''])
Reports an error identified by $message
if the variable $actual
is not of type $expected
.
$expected
can be one of these constants:
PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY
("array"
)PHPUnit_Framework_Constraint_IsType::TYPE_BOOL
("bool"
)PHPUnit_Framework_Constraint_IsType::TYPE_FLOAT
("float"
)PHPUnit_Framework_Constraint_IsType::TYPE_INT
("int"
)PHPUnit_Framework_Constraint_IsType::TYPE_NULL
("null"
)PHPUnit_Framework_Constraint_IsType::TYPE_NUMERIC
("numeric"
)PHPUnit_Framework_Constraint_IsType::TYPE_OBJECT
("object"
)PHPUnit_Framework_Constraint_IsType::TYPE_RESOURCE
("resource"
)PHPUnit_Framework_Constraint_IsType::TYPE_STRING
("string"
)assertNotType()
is the inverse of this assertion and takes the same arguments.
assertAttributeType()
and assertAttributeNotType()
are convenience wrappers that use a public
, protected
, or private
attribute of a class or object as the actual value.
Example 22.36: Usage of assertType()
<?php
class TypeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertType(PHPUnit_Framework_Constraint_IsType::TYPE_STRING, 2204);
}
public function testFailure2()
{
$this->assertType('string', 2204);
}
public function testFailure3()
{
$this->assertType('Exception', new stdClass);
}
}
?>
phpunit TypeTest
PHPUnit 3.4.2 by Sebastian Bergmann.
FFF
Time: 0 seconds
There were 3 failures:
1) testFailure(TypeTest)
Failed asserting that <integer:2204> is of type "string".
/home/sb/TypeTest.php:6
2) testFailure2(TypeTest)
Failed asserting that <integer:2204> is of type "string".
/home/sb/TypeTest.php:11
3) testFailure3(TypeTest)
Failed asserting that <stdClass> is an instance of class "Exception".
/home/sb/TypeTest.php:16
FAILURES!
Tests: 3, Assertions: 3, Failures: 3.
assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile[, string $message = ''])
Reports an error identified by $message
if the XML document in $actualFile
is not equal to the XML document in $expectedFile
.
assertXmlFileNotEqualsXmlFile()
is the inverse of this assertion and takes the same arguments.
Example 22.37: Usage of assertXmlFileEqualsXmlFile()
<?php
class XmlFileEqualsXmlFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlFileEqualsXmlFile(
'/home/sb/expected.xml', '/home/sb/actual.xml');
}
}
?>
phpunit XmlFileEqualsXmlFileTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(XmlFileEqualsXmlFileTest)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<foo>
- <bar/>
+ <baz/>
</foo>
/home/sb/XmlFileEqualsXmlFileTest.php:7
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
assertXmlStringEqualsXmlFile(string $expectedFile, string $actualXml[, string $message = ''])
Reports an error identified by $message
if the XML document in $actualXml
is not equal to the XML document in $expectedFile
.
assertXmlStringNotEqualsXmlFile()
is the inverse of this assertion and takes the same arguments.
Example 22.38: Usage of assertXmlStringEqualsXmlFile()
<?php
class XmlStringEqualsXmlFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlFile(
'/home/sb/expected.xml', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlFileTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(XmlStringEqualsXmlFileTest)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<foo>
- <bar/>
+ <baz/>
</foo>
/home/sb/XmlStringEqualsXmlFileTest.php:7
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
assertXmlStringEqualsXmlString(string $expectedXml, string $actualXml[, string $message = ''])
Reports an error identified by $message
if the XML document in $actualXml
is not equal to the XML document in $expectedXml
.
assertXmlStringNotEqualsXmlString()
is the inverse of this assertion and takes the same arguments.
Example 22.39: Usage of assertXmlStringEqualsXmlString()
<?php
class XmlStringEqualsXmlStringTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlString(
'<foo><bar/></foo>', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlStringTest
PHPUnit 3.4.2 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testFailure(XmlStringEqualsXmlStringTest)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<foo>
- <bar/>
+ <baz/>
</foo>
/home/sb/XmlStringEqualsXmlStringTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
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 22.2 lists the
bottlenext methods in PHPUnit.
Table 22.2. Bottleneck Methods
Method | Meaning |
---|---|
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.
Table 22.3. Marking a test as being incomplete or skipped
Method | Meaning |
---|---|
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 attributes. The
readAttribute()
method enables you to do this and
returns the value of a given (static) attribute from a given class or
object.
Table 22.4. Accessing non-public attributes
Method | Meaning |
---|---|
Mixed readAttribute($classOrObject, $attributeName) | Returns the value of a given (static) attribute ($attributeName ) of a class or of an object. This also works for attributes that are declared protected or private . |
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 22.5.
Table 22.5. Implementor Methods
Method | Meaning |
---|---|
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.
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 22.6 shows the
methods provided by PHPUnit_Framework_TestCase
.
Table 22.6. TestCase
Method | Meaning |
---|---|
__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($originalClassName, [array $methods, [array $arguments, [string $mockClassName, [boolean $callOriginalConstructor, [boolean $callOriginalClone, [boolean $callAutoload]]]]]]) | Returns a mock object (see Chapter 11) for the class specified by $originalClassName . 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. The fifth (optional) parameter can be used to disable the call to the original object's __construct() method. The sixth (optional) parameter can be used to disable the call to the original object's __clone() method. The seventh (optional) parameter can be used to disable __autoload() during mock object creation. |
object getMockForAbstractClass($originalClassName, [array $arguments, [string $mockClassName, [boolean $callOriginalConstructor, [boolean $callOriginalClone, [boolean $callAutoload]]]]]) | Returns a mock object (see Chapter 11) for the abstract class specified by $originalClassName . All abstract methods of the given abstract class are mocked. This allows for testing the concrete methods of an abstract class. |
object getMockFromWsdl($wsdlFile, [string $originalClassName, [string $mockClassName, [array $methods, [boolean $callOriginalConstructor) | Returns a mock object (see Chapter 11) for the SOAP web services described in $wsdlFile . |
void iniSet(string $varName, mixed $newValue) | This method is a wrapper for the ini_set() function that automatically resets the modified php.ini setting to its original value after the test is run. |
void setLocale(integer $category, string $locale, ...) | This method is a wrapper for the setlocale() function that automatically resets the locale to its original value after the test is run. |
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 22.7 shows
these methods. The template methods assertPreConditions()
and assertPostConditions()
can be used to define
assertions that should be performed by all tests of a test case class.
Table 22.7. Template Methods
Method | Meaning |
---|---|
void setUp() | Override to set up the fixture, for example create an object graph. |
void assertPreConditions() | Override to perform assertions shared by all tests of a test case class. This method is called before the execution of a test starts and after setUp() is called. |
void assertPostConditions() | Override to perform assertions shared by all tests of a test case class. This method is called before the execution of a test ends and before tearDown() is called. |
void tearDown() | Override to tear down the fixture, for example clean up an object graph. |
A PHPUnit_Framework_TestSuite
is a composite of
PHPUnit_Framework_Test
s. 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 22.8 shows the
methods to create PHPUnit_Framework_TestSuite
instances.
Table 22.8. Creating named or unnamed instances
Method | Meaning |
---|---|
__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. |
void markTestSuiteSkipped(string $message) | Marks the current test suite as being skipped, $message is optional. |
PHPUnit_Framework_TestSuite
also provides methods
for adding and retrieving PHPUnit_Framework_Test
s,
as shown in Table 22.9.
Table 22.9. Adding and retrieving tests
Method | Meaning |
---|---|
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 22.40 shows how to create and run a test suite.
Example 22.40: 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 7 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.
Table 22.10. Template Methods
Method | Meaning |
---|---|
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. |
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 22.11 summarizes
the API of PHPUnit_Framework_TestResult
.
Table 22.11. TestResult
Method | Meaning |
---|---|
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 wasSuccessful() | 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 22.12.
Table 22.12. TestResult and TestListener
Method | Meaning |
---|---|
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 22.13 shows the methods that test listeners implement; also see Example 23.3.
Table 22.13. TestListener Callbacks
Method | Meaning |
---|---|
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. |
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.
Prev | Next |
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertLessThan()
assertLessThanOrEqual()
assertNotNull()
assertObjectHasAttribute()
assertRegExp()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertType()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
Copyright © 2005-2009 Sebastian Bergmann.