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

  • Ethical AI in Agile
  • A Modern Stack for Building Scalable Systems
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Practical PHP Testing Patterns: Test Spy

Practical PHP Testing Patterns: Test Spy

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Mar. 09, 11 · Interview
Likes (0)
Comment
Save
Tweet
Share
3.0K Views

Join the DZone community and get the full member experience.

Join For Free

The concept of behavior verification consists in verifying not only the output of the System Under Test, but the calls to other components. These method calls are an output normally not visible to a caller like the test; unless he injects, instead of the real collaborator, a Test Double which can be accessed also by him.

Today we will explore the first pattern for behavior verification: the Test Spy. It is a Test Double which records calls so that assertions can be made on them later in the test (after the exercise part).

Spies gives us the ability to observe side-effects of the SUT, expressed as interactions with other objects. Usually behavior verification is taught with Mocks, which also verify the calls that are made on them but with specifications provided before the exercise phase.

Use cases

Why using a Spy instead a Mock? I bet you have heard already about Mocks at this point in the series. Here are some possible use cases on when to define Test Spies.

  • When we cannot predict what the collaborator will be called with (if we can, we may use a Mock instead).
  • When an assertion on calls is complex to define beforehand, or needs all (or more than one of) the calls to be completed before taking place.
  • The matchers used for Mocks are not sufficient for verification.
  • When a Mock that immediately threw an exception would only result in the SUT swallowing it. So a Spy is better in this case as it leaves verification for later. PHPUnit matchers in general do not always throw an exception or always wait for the end of test (it depends on the particular constraint.)
  • The behavior involves more than one collaborator (it happens sometimes). In this case, you can make an assertion using the data recorded by more than one Spy.

Implementation

1. Like with all Test Doubles, provide an alternate implementation or subclass. Probably the calls to the Spy won't return anything (or will return something canned to avoid the SUT's failure, like in a Stub). The methods implementations will just record all calls, or some property of the calls like the first parameter or their total number.

2. Inject the Test Double and exercise the SUT.

3. Make assertions on the Test Double data gathered by the Spy.

Variations

The variations of the pattern are mainly on how to retrieve the data from the Test Spy.

  • Retrieval Interface: the Test Spy is a class with additional methods, or public properties (eek) that expose the recorded data. This variation cannot be coded with PHPUnit generation of Test Doubles, only by hand-rolling them.
  • Self Shunt: the Test Spy and Test Case Object are a single object. This means we inject $this as the Test Double and we have the maximum freedom of defining new methods and access the recording. The caveat is that it can only be done with interfaces in PHPUnit, because Test Case Classes must extend PHPUnit_Framework_TestCase. That's a good reason to extract an interface, though.
  • Inner Test Double: we inject a private class (not existent in PHP) or a closure which records everything. A closure for example can access $this public properties or methods, or some other local ArrayObject passed by handler (or variable passed by reference) where the data can be kept.
  • Indirect Output Registry: same as Inner Test Double, but the target for recordings is a full-fledged object. Almost always an overkill.

Examples

The sample code shows you how to implement a Spy, in its different variations and in use cases where it actually make sense. Most of the times, Mock are used instead and the pattern is equivalent. Test Spies are a little more difficult to write, but they are invaluable in the case where your verification logic does not fit the framework of Mocks (predefined, single-object expectations).

<?php
class TestSpyTest extends PHPUnit_Framework_TestCase implements Mailer, Db
{
/**
* Other expectations would be simple to check with generated Mocks,
* but order of calls on different object is not in PHPUnit.
* The same Self-Shunting setup can be used in other tests too.
*/
public function testSendsAMailAfterUserCreationViaSelfShunting()
{
// remember, Db and Mailer would be two different objects in production
$sut = new UserDao($this, $this);
$sut->createUser(array('mail' => 'someone@example.com', 'nickname' => 'johndoe'));
$this->assertEquals(array('executeQuery', 'mail'), $this->order);
}

private $order = array();

private $queries = array();

public function executeQuery($query, array $params)
{
$this->order[] = 'executeQuery';
$this->queries[] = $query;
}

private $mails = array();

public function mail($to, $subject, $object)
{
$this->order[] = 'mail';
$this->mails[] = array('to' => $to,
'subject' => $subject,
'object' => $object);
}

public function testInnerTestDoubleArrayObject()
{
$parts = new ArrayObject();
$receiver = $this->getMock('Receiver');
$receiver->expects($this->any())
->method('definePart')
->will($this->returnCallback(function($amount) use ($parts) {
$parts[] = $amount;
}));
$sut = new RandomDivider($receiver);
$sut->divide(10);
$this->assertEquals(10, array_sum($parts->getArrayCopy()));
}

public function testInnerTestDoubleArrayPassedByReference()
{
$parts = array(); // an array would not be passed by handler by default
$receiver = $this->getMock('Receiver');
$receiver->expects($this->any())
->method('definePart')
->will($this->returnCallback(function($amount) use (&$parts) { // but we can pass it by reference
$parts[] = $amount;
}));
$sut = new RandomDivider($receiver);
$sut->divide(10);
$this->assertEquals(10, array_sum($parts));
}
}

interface Mailer
{
public function mail($to, $subject, $object);
}

interface Db
{
public function executeQuery($query, array $params);
}

class UserDao
{
private $db;
private $mailer;

public function __construct(DB $db, Mailer $mailer)
{
$this->db = $db;
$this->mailer = $mailer;
}

public function createUser(array $userDetails)
{
// internally it would use PDO
$this->db->executeQuery("INSERT INTO users ...", $userDetails);
$this->mailer->mail($userDetails['mail'], 'You have been registered on example.com', '...');
}
}

interface Receiver
{
public function definePart($amount);
}

class RandomDivider
{
private $receiver;

public function __construct(Receiver $receiver)
{
$this->receiver = $receiver;
}

public function divide($total)
{
$part = ceil(rand() * $total);
$this->receiver->definePart($part);
$this->receiver->definePart($total - $part);
}
}
Testing PHP Test double

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!