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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Modern Test Automation With AI (LLM) and Playwright MCP
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization

Trending

  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  • Enforcing Architecture With ArchUnit in Java
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Testing Patterns: Chained Tests

Practical PHP Testing Patterns: Chained Tests

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Jan. 24, 11 · Interview
Likes (0)
Comment
Save
Tweet
Share
4.4K Views

Join the DZone community and get the full member experience.

Join For Free

Sometimes you have tests where the fixtures can be recyled, instead of being recreated; but that's not all: sometimes, even the state reset we preach for Shared Fixture gets in the way instead of being mandatory.

For example, think of testing addition and removal of values over a collection object: to test the removal, you need a collection containing something. But this collection has to be populated somewhere, involving other methods which would have their own independent tests. If you look closer, however, you notice that the collection you need for testing values removal is just like the one that testAddsElements() produces when it succeeds, and simply throws away when the Test Methods returns...

The pattern

In these cases, the Chained Tests pattern can help you design isolated tests, by expressing the dependencies they implicitly have.

The application of this pattern results in a form of Api encapsulation: a test that tests Collection::remove() does not need to use Collection::add(), and won't be influenced by a change in the name or the signature of add(), which it does not focus on. The test just needs just a collection which has been already filled with values. Before "spolverare" unserialization and other strange techniques, just consider using the leftovers from a previous test.

Let's suppose we have two tests A and B, where B uses a variable produced in A. Of course, if A fails, the dependent Test Method B cannot (and shouldn't) be run; it will only add noise with an obvious failure which derives not from the behavior really under test there, but just from the fixture setup, which happens to be the previous test. If A instead runs correctly, B can be run.

Implementation

In PHPUnit, Chained Tests are supported when they are in the same Testcase Class. In this case, the Testcase Objects are not totally isolated anymore: you can return variables and objects from one test, in order for PHPUnit to pass them to other tests, that simply asks for them as dependencies.

You can do so by adding @depends annotation to dependent tests. Note that this annotation can also be used without passing fixtures around, just for the sake of not executing complex tests where the base ones have already failed.

@depends working by stopping the execution of tests down in the chain when the dependencies fail: they will be marked as skipped and signaled by an S in PHPUnit's ordinary output.

  • The tests which produce a fixture as a leftover must return that fixture at the end of the test.
  • The tests accepting fixtures, tagged with @depends, must accept parameters in the Test Method signatures.
  • In case of multiple parameters to return, you can return an array() and use list() in the dependent method to extract variables from it.

There is a known issue in running dependent tests with --filter: dependent tests would not run alone, so if you plan to use filter you may want to pick similar test names for couples of dependent/dependency in order to execute both of them when needed.

Example

Here we have a sample Testcase Class where the second and third tests are dependent on the first. Long chains of tests are not encouraged as it becomes increasingly difficult to tell what is the state of the fixture in the tests at the end of chain.

<?php
class ArrayTest extends PHPUnit_Framework_TestCase
{
public function testArrayAcceptsNewValues()
{
$array = array(4, 8);
// this won't work: if you chain two tests to this one
// the object won't be cloned
// $array = new ArrayObject(array(4, 8));
$array[] = 15;

$this->assertEquals(15, $array[2], 'The third element was not 15.');

return $array;
}

/**
* @depends testArrayAcceptsNewValues
*/
public function testArrayCanDeleteValues($array)
{
unset($array[2]);

$this->assertEquals(2, count($array), 'There are more than 2 elements in the array.');
}

/**
* @depends testArrayAcceptsNewValues
*/
public function testArrayAcceptsDuplicateValues($array)
{
$array[] = 15;

$this->assertEquals(4, count($array), 'There are less than 4 elements in the array.');
}
}

If we execute the whole test case, we obtain:

[10:40:55][giorgio@Desmond:~]$ phpunit txt/articles/chainedtest.php 
PHPUnit 3.5.5 by Sebastian Bergmann.

...

Time: 0 seconds, Memory: 5.00Mb

OK (3 tests, 3 assertions)

If we put a $this->fail() in the first test, instead, we get:

[10:41:40][giorgio@Desmond:~]$ phpunit txt/articles/chainedtest.php 
PHPUnit 3.5.5 by Sebastian Bergmann.

FSS

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) ArrayTest::testArrayAcceptsNewValues

/home/giorgio/Dropbox/txt/articles/chainedtest.php:13

FAILURES!
Tests: 1, Assertions: 1, Failures: 1, Skipped: 2.

If we filter the second test, we cannot run it due to the missing dependency:

[10:49:25][giorgio@Desmond:~]$ phpunit --filter testArrayCan txt/articles/chainedtest.php 
PHPUnit 3.5.5 by Sebastian Bergmann.

S

Time: 0 seconds, Memory: 4.75Mb

OK, but incomplete or skipped tests!
Tests: 0, Assertions: 0, Skipped: 1.

But if we filter the third test, thanks to the well-chosen name, we get:

[10:49:16][giorgio@Desmond:~]$ phpunit --filter testArrayAccepts txt/articles/chainedtest.php 
PHPUnit 3.5.5 by Sebastian Bergmann.

..

Time: 0 seconds, Memory: 5.00Mb

OK (2 tests, 2 assertions)
Testing PHP

Opinions expressed by DZone contributors are their own.

Related

  • Modern Test Automation With AI (LLM) and Playwright MCP
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!