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. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Practical PHP Testing Patterns: Hard-Coded Test Double

Practical PHP Testing Patterns: Hard-Coded Test Double

Giorgio Sironi user avatar by
Giorgio Sironi
·
Mar. 23, 11 · Interview
Like (0)
Save
Tweet
Share
2.37K Views

Join the DZone community and get the full member experience.

Join For Free

Sometimes 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);
    }
}
Test double PHP Test stub

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Front-End Troubleshooting Using OpenTelemetry
  • Testing Repository Adapters With Hexagonal Architecture
  • DevOps vs Agile: Which Approach Will Win the Battle for Efficiency?
  • Understanding and Solving the AWS Lambda Cold Start Problem

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: