DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Testing Patterns: Delegated Setup

Practical PHP Testing Patterns: Delegated Setup

Giorgio Sironi user avatar by
Giorgio Sironi
·
Dec. 29, 10 · Interview
Like (0)
Save
Tweet
Share
835 Views

Join the DZone community and get the full member experience.

Join For Free

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;
}
}
PHP Testing Fixture (tool) Test method

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Understanding and Solving the AWS Lambda Cold Start Problem
  • Building the Next-Generation Data Lakehouse: 10X Performance
  • The Power of Zero-Knowledge Proofs: Exploring the New ConsenSys zkEVM
  • Building a RESTful API With AWS Lambda and Express

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: