PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 18 ■ TESTING WITH PHPUNIT

after an error if for example an operation is half complete before the problem occurs? It is your role as a
tester to check all of this. Luckily, PHPUnit can help.
Here is a test that checks the behavior of the UserStore class when an operation fails:


//...
public function testAddUser_ShortPass() {
try {
$this->store->addUser( "bob williams", "[email protected]", "ff" );
} catch ( Exception $e ) { return; }
$this->fail("Short password exception expected");
}
//...


If you look back at the UserStore::addUser() method, you will see that I throw an exception if the
user’s password is less than five characters long. My test attempts to confirm this. I add a user with an
illegal password in a try clause. If the expected exception is thrown, then all is well, and I return silently.
The final line of the method should never be reached, so I invoke the fail() method there. If the
addUser() method does not throw an exception as expected, the catch clause is not invoked, and the
fail() method is called.
Another way to test that an exception is thrown is to use an assertion method called
setExpectedException(), which requires the name of the exception type you expect to be thrown (either
Exception or a subclass). If the test method exits without the correct exception having been thrown, the
test will fail.
Here’s a quick reimplementation of the previous test:


require_once('PHPUnit/Framework/TestCase.php');
require_once('UserStore.php');


class UserStoreTest extends PHPUnit_Framework_TestCase {
private $store;


public function setUp() {
$this->store = new UserStore();
}


public function testAddUser_ShortPass() {
$this->setExpectedException('Exception');
$this->store->addUser( "bob williams", "[email protected]", "ff" );
}
}


Running Test Suites


If I am testing the UserStore class, I should also test Validator. Here is a cut-down version of a class
called ValidateTest that tests the Validator::validateUser() method:


require_once('UserStore.php');
require_once('Validator.php');
require_once('PHPUnit/Framework/TestCase.php');


class ValidatorTest extends PHPUnit_Framework_TestCase {
private $validator;

Free download pdf