CHAPTER 18 ■ TESTING WITH PHPUNIT
up a stable and suitably primed environment for the test. tearDown() is invoked after each test method is
run. If your tests change the wider environment of your system, you can use this method to reset state.
The common platform managed by setUp() and tearDown() is known as a fixture.
In order to test the UserStore class, I need an instance of it. I can instantiate this in setUp() and
assign it to a property. Let’s create a test method as well:
require_once('UserStore.php');
require_once('PHPUnit/Framework/TestCase.php');
class UserStoreTest extends PHPUnit_Framework_TestCase {
private $store;
public function setUp() {
$this->store = new UserStore();
}
public function tearDown() {
}
public function testGetUser() {
$this->store->addUser( "bob williams", "[email protected]", "12345" );
$user = $this->store->getUser( "[email protected]" );
$this->assertEquals( $user['mail'], "[email protected]" );
$this->assertEquals( $user['name'], "bob williams" );
$this->assertEquals( $user['pass'], "12345" );
}
}
Test methods should be named to begin with the word “test” and should require no arguments. This
is because the test case class is manipulated using reflection.
■Note Reflection is covered in detail in Chapter 5.
The object that runs the tests looks at all the methods in the class and invokes only those that match
this pattern (that is, methods that begin with “test”).
In the example, I tested the retrieval of user information. I don’t need to instantiate UserStore for
each test, because I handled that in setUp(). Because setUp() is invoked for each test, the $store
property is guaranteed to contain a newly instantiated object.
Within the testGetUser() method, I first provide UserStore::addUser() with dummy data, then I
retrieve that data and test each of its elements.
Assertion Methods
An assertion in programming is a statement or method that allows you to check your assumptions about
an aspect of your system. In using an assertion you typically define an expectation that something is the
case, that $cheese is "blue" or $pie is "apple". If your expectation is confounded, a warning of some kind
will be generated. Assertions are such a good way of adding safety to a system that some programming