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: Testcase Superclass

Practical PHP Testing Patterns: Testcase Superclass

Giorgio Sironi user avatar by
Giorgio Sironi
·
Apr. 25, 11 · Interview
Like (0)
Save
Tweet
Share
853 Views

Join the DZone community and get the full member experience.

Join For Free

Oh my God, here's a duplication in test code. What do we do?
If you answered nothing, go back to square 1. Test code is like production code: I like to say that we should give him the same dignity.

A common refactoring that we already saw and comes to mind here is extracting a Test Utility Method. But what if the duplicated code has to be shared across classes?

It's not uncommon to find that assertion methods are continuosly rewritten in different classes, or that methods that build test objects are shared statically. There's more than one solution for sharing code, but a natural one is a Testcase Superclass: a base class that you can inherit protected methods from.

Implementation

Create a superclass that extends PHPUnit_Framework_TestCase; it should be abstract and do not contain many (or any) test methods, in the majority of cases.

Then have the current Testcase Classes that share code extend it: copy common code there, progressively deleting the overrides and maintaining a green bar all the time.
You can have more than one level of Testcases Superclasses, but be wary of infinite hierarchies as you will continuosly jump from one to the other to find out where a method is defined.

A problem with this pattern (and with inheritance in general) is that all languages, and also PHP, let you inherit from one parent class only. So when someone else already played the inheritance card, you won't be able to fully use this pattern. For example, Zend_Test provides a basic PHPUnit Testcase Class for testing Zend Framework application controllers: if you already have a base class that provides many utility methods, you're out of luck as you cannot extend both (don't despair however: there are other solutions.)

Variation

The Test Helper Mixin variation of this pattern prescribes to use mixins to solve the multiple inheritance problem, but in PHP they will arrive only in the next major releases of the interpreter; and it's not even said that mixins are actually a good idea since they are a compiler-assisted copy&paste tool.

Another variation I think is worth distinguishing is when the superclass actually include test*() methods; this means that test will be executed once for each concrete class. It also can be a smell that the classes have common functionality, which could be extracted. It happens often when using inheritance based solutions: you're tempted to rebuild the same inheritance hierarchy also with test code (nevertheless, it's duplication: when you change a class in the hierarchy you have to update the other hierarchy.)

You can in some cases try to use composition: you'll test in isolation by injecting a mock and the common funcionality will be in another concrete class with its own unit tests.

Examples

The example shows you the picture before the cure (two Testcase Classes with code duplication) and after it (the lean Testcase Classes and their superclass.

We have two testcases with some duplication between them:

<?php
require_once 'SUT.php';

/**
 * Before the refactoring.
 */
class FirstTest extends PHPUnit_Framework_TestCase
{
    public function testUsersCanBeDeletedByTheirIds()
    {
        $connection = new PDO("sqlite::memory:");
        $sut = new SUT($connection);
        // CREATE TABLE users...
        // INSERT users...
        $sut->deleteUser(array(1, 2));
        $this->assertEquals(0, count($sut->getUsers()));
    }
}
<?php
require_once 'SUT.php';

/**
 * Before the refactoring, we have some database plumbing code 
 * duplicated between here and FirstTest.
 * Sometimes we can merge the Testcase Classes, but if they are on 
 * different SUTs it becomes difficult and it would not scale.
 */
class SecondTest extends PHPUnit_Framework_TestCase
{
    public function testUsersDetailsCanBeModified()
    {
        $connection = new PDO("sqlite::memory:");
        $sut = new SUT($connection);
        // CREATE TABLE users...
        // INSERT users...
        $sut->updatePassword(1, 'oldPassword', 'newPassword');
        $this->assertEquals('newPassword', $sut->getUser(1)->getPassword());
    }
}

But if we extract a common Testcase Superclass:

<?php
/**
 * The extracted Testcase Superclass: abstract, protected 
 * Test Utility Methods and good Api documentation to foster its usage.
 */
abstract class UsersTest extends PHPUnit_Framework_TestCase
{
    /**
     * @return PDO  with schema created
     */
    protected function getDatabase()
    {
        $connection = new PDO("sqlite::memory:");
        // CREATE TABLE users...
        return $connection;
    }

    protected function createUser($details)
    {
        // INSERT INTO users...
    }
}

The test cases become much smaller:

<?php
require_once 'SUT.php';
require_once 'UsersTest.php';

/**
 * After the refactoring.
 */
class FirstAfterTest extends UsersTest
{
    public function testUsersCanBeDeletedByTheirIds()
    {
        $sut = new SUT($this->getDatabase());
        $this->createUser(array(/* ... */));
        $this->createUser(array(/* ... */));

        $sut->deleteUser(array(1, 2));
        $this->assertEquals(0, count($sut->getUsers()));
    }
}
<?php
require_once 'SUT.php';
require_once 'UsersTest.php';

/**
 * After the refactoring.
 */
class SecondAfterTest extends UsersTest
{
    public function testUsersDetailsCanBeModified()
    {
        $sut = new SUT($this->getDatabase());
        $this->createUser(array(/* ... */));
        $sut->updatePassword(1, 'oldPassword', 'newPassword');
        $this->assertEquals('newPassword', $sut->getUser(1)->getPassword());
    }
}
PHP

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Getting a Private SSL Certificate Free of Cost
  • What’s New in Flutter 3.7?
  • DeveloperWeek 2023: The Enterprise Community Sharing Security Best Practices
  • 5 Common Firewall Misconfigurations and How to Address Them

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: