Practical PHP Testing Patterns: Hard-Coded Test Double
Join the DZone community and get the full member experience.
Join For FreeSometimes we want to build a Test Double class that would serve for only one object, or for multiple objects that are used in exactly the same context. Building a Configurable Test Double, even when generation is involved, may be an overkill and a violation of the KISS principle.
Thus in this scenarios all returned values and expected calls can be hard-coded in the source code of the Test Double.
When to use this pattern
Of course, the behavior of the collaborator in the current test must be very simple in order for an Hard-Coded Test Double to be implemented. For example, different return values in multiple calls to a method are already out of the scope of the pattern.
An advantage of the Hard-Coded Test Double resides in being very clear and readable, without requiring to understand the mocking framework's primitives.
This kind of doubles are very specific to a test, but getMock() (generation approach) is also very quick in this case, especially when you have the flexibility of returnCallback() too. A corner case where hardcoding is widely used is in self-shunting (when the Testcase Object becomes a Test Double).
Implementation
The Test Double code must have hard-coded assertions and hard-coded return statements, which are essential for retaining simplicity. It's problematic to reuse these doubles in different contexts, so they don't need their own sourcefile and can stay in the .php file of the Testcase Class itself.
Since in PHP there is no support for private classes, the use of namespaces can help avoid naming collisions when running the whole suite (and thus including all the different double classes in one process). If you do not use PHP 5.3 namespaces, insert a folder-based prefix in the class names of the Hard-Coded Test Doubles.
Doubles may need the injection of $this (the Testcase Object) for performing assertions, or can just throw Exceptions if the SUT allows it.
Fragility
Hard-Coded Doubles are a subset of hand-rolled Test Doubles. The difference is that the latter can contain complex methods (even be a Fake), while the former is specifically kept simple.
Hand-rolled doubles are commonly considered fragile as they are not updated automatically when the contract they implement changes. However, Uncle Bob wrote about hand-rolled (and so also hard-coded) doubles being fragile:
Yes, they can be. If you are mocking a class or interface that it very volatile (i.e. you are adding new methods, or modifying method signatures a lot) then you’ll have to go back and maintain all your hand-rolled mocks every time you make such a change. On the other hand, if you use a mocking framework, the framework will take care of that for you unless one of the methods you are specifically testing is modified.
But here’s the thing. Interfaces should not usually be volatile. They should not continue to grow and grow, and the methods should not change much. OK, I realize that’s wishful thinking. But, yes, I wish for the kind of a design in which interfaces are the least volatile source files that you have. That’s kind of the point of interfaces after all… You create interfaces so that you can separate volatile implementations from non-volatile clients. (Or at least that’s one reason.)
Examples
The example modifies the scenario of the Test Stub article in order to use Hard-Coded Doubles. Naming and simplicity are key points to look for in this code.
<?php /** * We expand the example of the Test Stub article in order to discuss * Hard-Coded Test Doubles. */ class HardCodedTestDoubleTest extends PHPUnit_Framework_TestCase { /** * This Test Double is hard-coded: since we have to define a class * for it externally to this Testcase Class, we lose a bit of readability. */ public function testCalculatesAverageVisitorsNumber() { $source = new FixedDataSource(); $statistics = new Statistics($source); $this->assertEquals(50000, $statistics->getAverage()); } /** * Sometimes a feel of what the Test Double does can be presented * by choosing a meaningful name. */ public function testWhenThereAreNoSamplesRemainsAtZeroVisits() { $source = new EmptyDataSource(); $statistics = new Statistics($source); $this->assertEquals(0, $statistics->getAverage()); } /** * And hard-coding can take place also in the name of the class, at a very * low level of abstraction. */ public function testCalculatesAverageVisitorsNumberUsingATestDoubleWithMeaningfulName() { $source = new DataSource40000And50000And60000(); $statistics = new Statistics($source); $this->assertEquals(50000, $statistics->getAverage()); } } /** * This is the contract of the source, the collaborator for the SUT. * It's not mandatory to have an explicit interface, particularly in PHP, * but it helps. */ interface DataSource { /** * @return array numerical values of visitors to this website */ public function getSamples(); } class FixedDataSource implements DataSource { public function getSamples() { return array(40000, 50000, 100000, 20000, 40000); } } class EmptyDataSource implements DataSource { public function getSamples() { return array(); } } class DataSource40000And50000And60000 implements DataSource { public function getSamples() { return array(40000, 50000, 100000, 20000, 40000); } } /** * The System Under Test (same as previous article). * It requires a DataSource collaborator to be used in production, * or to be tested. */ class Statistics { private $source; public function __construct(DataSource $source) { $this->source = $source; } public function getAverage() { $samples = $this->source->getSamples(); if (!$samples) { return 0; } return array_sum($samples) / count($samples); } }
Opinions expressed by DZone contributors are their own.
Comments