Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 638 posts at DZone. You can read more from them at their website. View Full User Profile

Practical PHP Testing Patterns: Delegated Setup

12.29.2010
| 5602 views |
  • submit to reddit

Inline Setup is pretty simple to understand: you just create the fixture when you need them, in the Test Method that needs them. But sometimes the process gets too long, or unreadable, or full of duplicated code between tests. So you have to factor out that creation logic. And where do you put it?

In the Delegated Setup pattern, Test Methods call Creation Methods that create their fixtures according to some parameters which are passed in.

Typically, the parameters describe the variability that the current Test Method introduces in the data, while the name of the method the standard part which is reused between tests. For example:

$this->createBlueIterator(array('A', 'B'));

will create a standard blue iterator (blue is just a placeholder for a characteristic, and iterator a loose pointer to a class or interface name.) However, the data this iterator works with in each test is different, and is passed in the creation method.

Of course the trade-off is that the more you standardize and extract in Creation Methods, the shorter the tests will be. But you should always keep an eye on readability of the creation Api and on keeping the fixture not too far from the Fresh Fixture end of the spectrum. The original code to factor out:

FreshFixture: $iterator = new BlueSpecialIterator(ArrayIterator(array('A', 'B')));

can easily become an intermediate example of Extract Method refactoring:

$iterator = $this->createBlueIterator(array('A', 'B'));

but also an obscure Standard Fixture example where who reads the code is left wondering what's inside:

$iterator = $this->createABlueIterator();

You should factor out not just what gets duplicated, but what you want to effectively hide. A little duplication between Test Methods is better than an Obscure Test.

Advantages

The main advantage of this pattern is that it eliminates duplication in any form. To be more specific, when used correctly it eliminates the noise of the duplication, to leave only the actual variable data in the test itself. It's easy to just extract everything but keep in mind that your assertions should make sense within the context of this setup. In the third example of setup seen earlier, an assertion referencing 'A' or 'B' would wake you up from writing a Creation Method like createBlueIterator(void).

 

Disadvantages

When abused, leads to tests with no arrange phase at all. This may be good, if the fixture is thought to be Standard, but lacks explicitness and makes the test hard to read when it's not the case.

We are all guilty of using the setUp() fixture only in 9 out of 10 tests of a class sometimes. But if those tests would be simpler with a Minimal Fixture instead of a Standard One, you should really consider to reorganize the creation code.

Even if you can just breakdown a Standard Fixture in two or three different ones which are simpler to create and grasp, the tests would get an high return on the investment. For example, the debugging in case a regression is found would be easier as there is not so much data to read. In any case, this pattern moves you from the Fresh/Minimal end of the fixture spectrum to the other end, Shared and Standard.

Example

This code sample will show you the refactoring of a Test Method from a complex Inline Setup to a Delegated Setup. In the third version, the refactoring goes too far and the test becomes hard to understand (at least it will be if you try to read that test, by itself, a week from now).

<?php
class DelegatesSetupTest extends PHPUnit_Framework_TestCase
{
/**
* This is the original Inline Setup which got complicate in the previous
* article.
*/
public function testInlineSetupOfAnAppendIterator()
{
$array = array('A');
$anotherArray = array('B');
$iterator = new AppendIterator();
$iterator->append(new ArrayIterator($array));
$iterator->append(new ArrayIterator($anotherArray));

$this->assertEquals('A', $iterator->current());
$iterator->next();
$this->assertEquals('B', $iterator->current());
$iterator->next();
$this->assertFalse($iterator->valid());
}

/**
* In my opinion this is as far as we can go without making the test harder
* to read. There is a whole science of how to extract Creation Methods,
* but we will see them in the next article of this series.
*/
public function testDelegatedSetupOfAnAppendIterator()
{
$iterator = $this->createAppendIterator(array(
new ArrayIterator(array('A')),
new ArrayIterator(array('B'))
));

$this->assertEquals('A', $iterator->current());
$iterator->next();
$this->assertEquals('B', $iterator->current());
$iterator->next();
$this->assertFalse($iterator->valid());
}

private function createAppendIterator(array $innerIterators)
{
$iterator = new AppendIterator();
foreach ($innerIterators as $it) {
$iterator->append($it);
}
return $iterator;
}

/**
* This is TOO MUCH. It hides the input of the test, so that we cannot
* reason on the assertions and the starting state at the same time.
*/
public function testTooMuchDelegatedSetupOfAnAppendIterator()
{
$iterator = $this->createAnAppendIterator();

$this->assertEquals('A', $iterator->current());
$iterator->next();
$this->assertEquals('B', $iterator->current());
$iterator->next();
$this->assertFalse($iterator->valid());
}

public function createAnAppendIterator()
{
$appendIterator = new AppendIterator();
$appendIterator->append(new ArrayIterator(array('A')));
$appendIterator->append(new ArrayIterator(array('B')));
return $appendIterator;
}
}
Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)