- Last edited February 18, 2003 |
Using the template method pattern makes testing easier. Simply create a test version of the (abstract?) class with the key method overridden. In particular, if the method is a factory one then this can be a way of injecting a MockObject into the class.
The type of test method you want is usually similar to the type you want in a generated mock, so it is no surprise that we have added this to our homebrew PHP mocks library. The following code (with LowercaseApology)...
mock::generate_partial("my_class", "test_version_of_my_class", array("this_method", "that_method"));
...allows us to create a new object...
$test_object = new test_version_of_my_class();
...and to set return values and record calls to this_method() and that_method(). Other methods remain the same of course as it is just a simple inheritance.
There are two purposes to this. One is testing the class with the templated method itself. The other more common one is where we require a mock with quite a lot of real behaviour. Usually this is from some kind of localised integration test. Now the partially mocked class is a test tool rather than the class under test.
There is more discussion of this at MockObjectsAndDemeter.
In 1899 unit tests (up to today) we have used this about 7 times. We have used it in integration tests to reduce test data about the same number of times. Not a great deal of use, but it has paid for it's small initial investment. - MarcuS
- Last edited February 18, 2003 |