PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 18 ■ TESTING WITH PHPUNIT

$this->assertEquals( $user->getMail(), "[email protected]" );
// ...


When I come to run my test suite, however, I am rewarded with a warning that my work is not yet
done:


$ php AppTests.php


PHPUnit 3.0.6 by Sebastian Bergmann.


...FF


Time: 00:00


There were 2 failures:




  1. testValidate_CorrectPass(ValidatorTest)
    Expecting successful validation
    Failed asserting that is identical to .
    /project/wibble/ValidatorTest.php:22




  2. testValidate_FalsePass(ValidatorTest)
    Expectation failed for method name is equal to
    when invoked 1 time(s).
    Expected invocation count is wrong.




FAILURES!
Tests: 5, Failures: 2.


There is a problem with ValidatorTest. Let’s take another look at the Validator::validateUser()
method:


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;
}


I invoke getUser(). Although getUser() now returns an object and not an array, my method does
not generate a warning. getUser() originally returned the requested user array on success or null on
failure, so I validated users by checking for an array using the is_array() function. Now, of course,
getUser() returns an object, and the validateUser() method will always return false. Without the test
framework, the Validator would have simply rejected all users as invalid without fuss or warning.
Now, imagine making this neat little change on a Friday night without a test framework in place.
Think about the frantic text messages that would drag you out of your pub, armchair, or restaurant,
“What have you done? All our customers are locked out!”

Free download pdf