PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 18 ■ TESTING WITH PHPUNIT


languages support them natively and inline and allow you to turn them off in a production context (Java
is an example). PHPUnit supports assertions though a set of static methods.
In the previous example, I used an inherited static method: assertEquals(). This compares its two
provided arguments and checks them for equivalence. If they do not match, the test method will be
chalked up as a failed test. Having subclassed PHPUnit_Framework_TestCase, I have access to a set of
assertion methods. Some of these methods are listed in Table 18–1.


Table 18–1. PHPUnit_Framework_TestCase Assert Methods


Method Description

assertEquals( $val1, $val2, $delta, $message) Fail if $val1 is not equivalent to $val2. ($delta
represents an allowable margin of error.)

assertFalse( $expression, $message) Evaluate $expression. Fail if it does not
resolve to false.

assertTrue( $expression, $message) Evaluate $expression. Fail if it does not
resolve to true.

assertNotNull( $val, $message ) Fail if $val is null.

assertNull( $val, $message ) Fail if $val is anything other than null.

assertSame( $val1, $val2, $message ) Fail if $val1 and $val2 are not references to
the same object or if they are variables of
different types or values.

assertNotSame( $val1, $val2, $message ) Fail if $val1 and $val2 are references to the
same object or variables of the same type and
value.

assertRegExp( $regexp, $val, $message ) Fail if $val is not matched by regular
expression $regexp.

assertType( $typestring, $val, $message ) Fail if $val is not the type described in $type.

assertAttributeSame($val, $attribute,
$classname, $message)

Fail if $val is not the same type and value as
$classname::$attribute.

fail() Fail.

Testing Exceptions


Your focus as a coder is usually to make stuff work and work well. Often, that mentality carries through
to testing, especially if you are testing your own code. The temptation is test that a method behaves as
advertised. It’s easy to forget how important it is to test for failure. How good is a method’s error
checking? Does it throw an exception when it should? Does it throw the right exception? Does it clean up

Free download pdf