CHAPTER 18 ■ TESTING WITH PHPUNIT
public function setUp() {
$store = new UserStore();
$store->addUser( "bob williams", "[email protected]", "12345" );
$this->validator = new Validator( $store );
}
public function tearDown() {
}
public function testValidate_CorrectPass() {
$this->assertTrue(
$this->validator->validateUser( "[email protected]", "12345" ),
"Expecting successful validation"
);
}
}
So now that I have more than one test case, how do I go about running them together? The best way
is to place your test classes in a directory called test. You can then specify this directory and
PHPUnit will run all the tests beneath it.
$ phpunit test/
PHPUnit 3.4.11 by Sebastian Bergmann.
.....
Time: 1 second, Memory: 3.75Mb
OK (5 tests, 10 assertions)
For a larger project you may want to further organize tests in subdirectories preferably in the same
structure as your packages. Then you can specify indivisual packages when required.
Constraints
In most circumstances, you will use off-the-peg assertions in your tests. In fact, at a stretch you can
achieve an awful lot with AssertTrue() alone. As of PHPUnit 3.0, however, PHPUnit_Framework_TestCase
includes a set of factory methods that return PHPUnit_Framework_Constraint objects. You can combine
these and pass them to PHPUnit_Framework_TestCase::AssertThat() in order to construct your own
assertions.
It’s time for a quick example. The UserStore object should not allow duplicate e-mail addresses to
be added. Here’s a test that confirms this:
class UserStoreTest extends PHPUnit_Framework_TestCase {
//....
public function testAddUser_duplicate() {
try {
$ret = $this->store->addUser( "bob williams", "[email protected]", "123456" );
$ret = $this->store->addUser( "bob stevens", "[email protected]", "123456" );