PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 18 ■ TESTING WITH PHPUNIT

This class accepts user data with the addUser() method and retrieves it via getUser(). The user’s
e-mail address is used as the key for retrieval. If you’re like me, you’ll write some sample implementation
as you develop, just to check that things are behaving as you designed them—something like this:


$store=new UserStore();
$store->addUser( "bob williams",
"[email protected]",
"12345" );
$user = $store->getUser( "[email protected]" );
print_r( $user );


This is the sort of thing I might add to the foot of a file as I work on the class it contains. The test
validation is performed manually, of course; it’s up to me to eyeball the results and confirm that the data
returned by UserStore::getUser() corresponds with the information I added initially. It’s a test of sorts,
nevertheless.
Here is a client class that uses UserStore to confirm that a user has provided the correct
authentication information:


class Validator {
private $store;


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


public function validateUser( $mail, $pass ) {
if (! is_array($user = $this->store->getUser( $mail )) ) {
return false;
}
if ( $user['pass'] == $pass ) {
return true;
}
$this->store->notifyPasswordFailure( $mail );
return false;
}
}


The class requires a UserStore object, which it saves in the $store property. This property is used by
the validateUser() method to ensure first of all that the user referenced by the given e-mail address
exists in the store and secondly that the user’s password matches the provided argument. If both these
conditions are fulfilled, the method returns true. Once again, I might test this as I go along:


$store = new UserStore();
$store->addUser( "bob williams", "[email protected]", "12345" );
$validator = new Validator( $store );
if ( $validator->validateUser( "[email protected]", "12345" ) ) {
print "pass, friend!\n";
}


I instantiate a UserStore object, which I prime with data and pass to a newly instantiated Validator
object. I can then confirm a user name and password combination.
Once I’m finally satisfied with my work, I could delete these sanity checks altogether or comment
them out. This is a terrible waste of a valuable resource. These tests could form the basis of a harness to
scrutinize the system as I develop. One of the tools that might help me to do this is PHPUnit.

Free download pdf