Previous Up Next
Reporting Simple Test PHP Unit Test Framework Web tester


Table of Contents

More control over mock objects

The default behaviour of the mock in SimpleTest is either an identical match on the argument or to allow any argument at all. For almost all tests this is sufficient. Sometimes, though, you want to weaken a test case.

One place where a test can be too tightly coupled is with text matching. Suppose we have a component that outputs a helpful error message when something goes wrong. You want to test that the correct error was sent, but the actual text may be rather long. If you test for the text exactly, then every time the exact wording of the message changes, you will have to go back and edit the test suite.

For example, suppose we have a news service that has failed to connect to its remote source.

  1. class NewsService {
  2.     ...
  3.     function publish($writer{
  4.         if ($this->isConnected()) {
  5.             $writer->write('Cannot connect to news service "' .
  6.                     $this->_name '" at this time. ' .
  7.                     'Please try again later.');
  8.         }
  9.         ...
  10.     }
  11. }
Here it is sending its content to a Writer class. We could test this behaviour with a MockWriter like so...
  1. class TestOfNewsService extends UnitTestCase {
  2.     ...
  3.     function testConnectionFailure({
  4.         $writer new MockWriter();
  5.         $writer->expectOnce('write'array(
  6.                 'Cannot connect to news service ' .
  7.                 '"BBC News" at this time. ' .
  8.                 'Please try again later.'));
  10.         $service new NewsService('BBC News');
  11.         $service->publish($writer);
  12.     }
  13. }
This is a good example of a brittle test. If we decide to add additional instructions, such as suggesting an alternative news source, we will break our tests even though no underlying functionality has been altered.

To get around this, we would like to do a regular expression test rather than an exact match. We can actually do this with...

  1. class TestOfNewsService extends UnitTestCase {
  2.     ...
  3.     function testConnectionFailure({
  4.         $writer new MockWriter();
  5.         $writer->expectOnce(
  6.                 'write',
  7.                 array(new PatternExpectation('/cannot connect/i')));
  9.         $service new NewsService('BBC News');
  10.         $service->publish($writer);
  11.     }
  12. }
Instead of passing in the expected parameter to the MockWriter we pass an expectation class called PatternExpectation. The mock object is smart enough to recognise this as special and to treat it differently. Rather than simply comparing the incoming argument to this object, it uses the expectation object itself to perform the test.

The PatternExpectation takes the regular expression to match in its constructor. Whenever a comparison is made by the MockWriter against this expectation class, it will do a preg_match() with this pattern. With our test case above, as long as "cannot connect" appears in the text of the string, the mock will issue a pass to the unit tester. The rest of the text does not matter.

The possible expectation classes are...

AnythingExpectation Will always match
EqualExpectation An equality, rather than the stronger identity comparison
NotEqualExpectation An inequality comparison
IndenticalExpectation The default mock object check which must match exactly
NotIndenticalExpectation Inverts the mock object logic
WithinMarginExpectation Compares a value to within a margin
OutsideMarginExpectation Checks that a value is out side the margin
PatternExpectation Uses a Perl Regex to match a string
NoPatternExpectation Passes only if failing a Perl Regex
IsAExpectation Checks the type or class name only
NotAExpectation Opposite of the IsAExpectation
MethodExistsExpectation Checks a method is available on an object
TrueExpectation Accepts any PHP variable that evaluates to true
FalseExpectation Accepts any PHP variable that evaluates to false
Most take the expected value in the constructor. The exceptions are the pattern matchers, which take a regular expression, and the IsAExpectation and NotAExpectation which takes a type or class name as a string.

Some examples...

  1. $mock->expectOnce('method'array(new IdenticalExpectation(14)));
This is the same as $mock->expectOnce('method', array(14)).
  1. $mock->expectOnce('method'array(new EqualExpectation(14)));
This is different from the previous version in that the string "14" as a parameter will also pass. Sometimes the additional type checks of SimpleTest are too restrictive.
  1. $mock->expectOnce('method'array(new AnythingExpectation(14)));
This is the same as $mock->expectOnce('method', array('*')).
  1. $mock->expectOnce('method'array(new IdenticalExpectation('*')));
This is handy if you want to assert a literal "*". This matches on anything other than integer 14. Even the string "14" would pass.
  1. new WithinMarginExpectation(14.00.001)
This will accept any value from 13.999 to 14.001 inclusive.

Using expectations to control stubs

The expectation classes can be used not just for sending assertions from mock objects, but also for selecting behaviour for the mock. Anywhere a list of arguments is given, a list of expectation objects can be inserted instead.

Suppose we want a mock authorisation server to simulate a successful login, but only if it receives a valid session object. We can do this as follows...

  1. Mock::generate('Authorisation');
  3. $authorisation new MockAuthorisation();
  4. $authorisation->returns(
  5.         'isAllowed',
  6.         true,
  7.         array(new IsAExpectation('Session''Must be a session')));
  8. $authorisation->returns('isAllowed'false);
We have set the default mock behaviour to return false when isAllowed is called. When we call the method with a single parameter that is a Session object, it will return true. We have also added a second parameter as a message. This will be displayed as part of the mock object failure message if this expectation is the cause of a failure.

This kind of sophistication is rarely useful, but is included for completeness.

Creating your own expectations

The expectation classes have a very simple structure. So simple that it is easy to create your own versions for commonly used test logic.

As an example here is the creation of a class to test for valid IP addresses. In order to work correctly with the stubs and mocks the new expectation class should extend SimpleExpectation or further extend a subclass...

  1. class ValidIp extends SimpleExpectation {
  3.     function test($ip{
  4.         return (ip2long($ip!= -1);
  5.     }
  7.     function testMessage($ip{
  8.         return "Address [$ip] should be a valid IP address";
  9.     }
  10. }
There are only two methods to implement. The test() method should evaluate to true if the expectation is to pass, and false otherwise. The testMessage() method should simply return some helpful text explaining the test that was carried out.

This class can now be used in place of the earlier expectation classes.

Here is a more typical example, matching part of a hash...

  1. class JustField extends EqualExpectation {
  2.     private $key;
  4.     function __construct($key$expected{
  5.         parent::__construct($expected);
  6.         $this->key $key;
  7.     }
  9.     function test($compare{
  10.         if (isset($compare[$this->key])) {
  11.             return false;
  12.         }
  13.         return parent::test($compare[$this->key]);
  14.     }
  16.     function testMessage($compare{
  17.         if (isset($compare[$this->key])) {
  18.             return 'Key [' $this->key '] does not exist';
  19.         }
  20.         return 'Key [' $this->key '] -> ' .
  21.                 parent::testMessage($compare[$this->key]);
  22.     }
  23. }
We tend to seperate message clauses with " -> ". This allows derivative tools to reformat the output.

Suppose some authenticator is expecting to be given a database row corresponding to the user, and we only need to confirm the username is correct. We can assert just their username with...

  1. $mock->expectOnce('authenticate',
  2.                   array(new JustKey('username''marcus')));

Under the bonnet of the unit tester

The SimpleTest unit testing framework also uses the expectation classes internally for the class.html UnitTestCase class. We can also take advantage of these mechanisms to reuse our homebrew expectation classes within the test suites directly.

The most crude way of doing this is to use the generic SimpleTest::assert() method to test against it directly...

  1. class TestOfNetworking extends UnitTestCase {
  2.     ...
  3.     function testGetValidIp({
  4.         $server &new Server();
  5.         $this->assert(
  6.                 new ValidIp(),
  7.                 $server->getIp(),
  8.                 'Server IP address->%s');
  9.     }
  10. }
assert() will test any expectation class directly.

This is a little untidy compared with our usual assert...() syntax.

For such a simple case we would normally create a separate assertion method on our test case rather than bother using the expectation class. If we pretend that our expectation is a little more complicated for a moment, so that we want to reuse it, we get...

  1. class TestOfNetworking extends UnitTestCase {
  2.     ...
  3.     function assertValidIp($ip$message '%s'{
  4.         $this->assert(new ValidIp()$ip$message);
  5.     }
  7.     function testGetValidIp({
  8.         $server &new Server();
  9.         $this->assertValidIp(
  10.                 $server->getIp(),
  11.                 'Server IP address->%s');
  12.     }
  13. }
It is rare to need the expectations for more than pattern matching, but these facilities do allow testers to build some sort of domain language for testing their application. Also, complex expectation classes could make the tests harder to read and debug. In effect extending the test framework to create their own tool set.

Previous Up Next
Reporting Simple Test PHP Unit Test Framework Web tester

Documentation generated on Sun, 31 Oct 2010 16:30:47 -0500 by phpDocumentor 1.4.3