PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 18 ■ TESTING WITH PHPUNIT


Introducing PHPUnit


PHPUnit is a member of the xUnit family of testing tools. The ancestor of these is SUnit, a framework
invented by Kent Beck to test systems built with the Smalltalk language. The xUnit framework was
probably established as a popular tool, though, by the Java implementation, jUnit, and by the rise to
prominence of agile methodologies like Extreme Programming (XP) and Scrum, all of which place great
emphasis on testing.
The current incarnation of PHPUnit was created by Sebastian Bergmann, who changed its name
from PHPUnit2 (which he also authored) early in 2007 and shifted its home from the pear.php.net
channel to pear.phpunit.de. For this reason, you must tell the pear application where to search for the
framework when you install:


$ pear channel-discover pear.phpunit.de
$ pear channel-discover pear.symfony-project.com
$ pear install phpunit


■Note I show commands that are input at the command line in bold to distinguish them from any output they


may produce.


Notice I added another channel, pear.symfony-project.com. This may be needed to satisfy a
dependency of PHPUnit that is hosted there.


Creating a Test Case


Armed with PHPUnit, I can write tests for the UserStore class. Tests for each target component should be
collected in a single class that extends PHPUnit_Framework_TestCase, one of the classes made available by
the PHPUnit package. Here’s how to create a minimal test case class:


require_once 'PHPUnit/Framework/TestCase.php';


class UserStoreTest extends PHPUnit_Framework_TestCase {


public function setUp() {
}


public function tearDown() {
}


//...
}


I named the test case class UserStoreTest. You are not obliged to use the name of the class you are
testing in the test’s name, though that is what many developers do. Naming conventions of this kind can
greatly improve the accessibility of a test harness, especially as the number of components and tests in
the system begins to increase. It is also common to group tests in package directories that directly mirror
those that house the system’s classes. With a logical structure like this, you can often open up a test from
the command line without even looking to see if it exists! Each test in a test case class is run in isolation
from its siblings. The setUp() method is automatically invoked for each test method, allowing us to set

Free download pdf