PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 18 ■ TESTING WITH PHPUNIT

repeatedly) that the associated method should be primed to return. You can pass in this return value by
calling either TestCase::returnValue() or TestCase::onConsecutiveCalls(). Once again, this is much
easier to do than to describe. Here’s the fragment from my earlier example in which I prime UserStore to
return a value:


$store->expects( $this->any() )
->method("getUser")
->will( $this->returnValue(
array( "name"=>"bob williams",
"mail"=>"[email protected]",
"pass"=>"right")));


I prime the UserStore mock to expect any number of calls to getUser()— right now, I’m concerned
with providing data and not with testing calls. Next, I call will() with the result of invoking
TestCase::returnValue() with the data I want returned (this happens to be a
PHPUnit_Framework_MockObject_Stub_Return object, though if I were you, I’d just remember the
convenience method you use to get it).
You can alternatively pass the result of a call to TestCase::onConsecutiveCalls() to will(). This
accepts any number of parameters, each one of which will be returned by your mocked method as it is
called repeatedly.


Tests Succeed When They Fail


While most agree that testing is a fine thing, you grow to really love it generally only after it has saved
your bacon a few times. Let’s simulate a situation where a change in one part of a system has an
unexpected effect elsewhere.
The UserStore class has been running for a while when, during a code review, it is agreed that it
would be neater for the class to generate User objects rather than associative arrays. Here is the new
version:


class UserStore {
private $users = array();


function addUser( $name, $mail, $pass ) {


if ( isset( $this->users[$mail] ) ) {
throw new Exception(
"User {$mail} already in the system");
}


$this->users[$mail] = new User( $name, $mail, $pass );
return true;
}


function notifyPasswordFailure( $mail ) {
if ( isset( $this->users[$mail] ) ) {
$this->users[$mail]->failed(time());
}
}


function getUser( $mail ) {
if ( isset( $this->users[$mail] ) ) {
return ( $this->users[$mail] );

Free download pdf