Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 638 posts at DZone. You can read more from them at their website. View Full User Profile

Practical PHP Testing Patterns: Testcase Superclass

04.25.2011
| 6104 views |
  • submit to reddit

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());
    }
}
Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)