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 637 posts at DZone. You can read more from them at their website. View Full User Profile

PHPUnit 3.5: easier asserting and mocking

09.26.2010
| 12659 views |
  • submit to reddit
The official release of PHPUnit 3.5 is now available for PEAR installation, after a long beta period. PHPUnit 3.5 provides many new features such as a bunch of new assertions methods and annotations, and a little but very useful contribution of mine: the MockBuilder.

Componentization

PHPUnit code base has been divided in several components that are bundled together via PEAR package dependencies. If the upgrade to PHPUnit 3.5 gives you some problems, a fresh install should fix them and download all the necessary packages:
sudo pear uninstall phpunit/PHPUnit
sudo pear install phpunit/PHPUnit
I ran also into some missing channels which PHPUnit grabs packages from:
sudo pear channel-discover pear.symfony-project.com
sudo pear channel-discover components.ez.no

I always prefer to install pear (and thus pecl) via the Ubuntu package manager, and then left the pear binary manage all the PHP-born packages, such as PHPUnit and Phing. This way, promptly upgrades are usually available and you do not end up mixing Ubuntu debs with downloaded packages, by simply enforcing a single mean of installation. The same reasoning can be made for other Linux distributions.

By the way, the componentization does not affect the ordinary user (only the contributors, which have to work on different git repositories), nor your tests. As you would expect from a minor release, the API of PHPUnit 3.x is only expanded with new features but kept backward compatible.

New assertions and annotations

Some handy new assertion methods have been introduced, and I'll give you a practical example later in this post. Calling these methods instead of constructing custom boolean conditions to pass to assertTrue() means clear failure messages without adding the additional $message assertion argument, and enhanced readability of the tests. You can easily extract custom assertions into their own methods, but having them on the base test case class makes it immediately available, everywhere.

MockBuilder

Finally, I'd like to talk about my little addition to PHPUnit mocking Api, which is an implementation of the Builder pattern for mock objects (inexplicably left out from the changelog published on Github).

As you may know, the 3.4 Api contains a getMock() method with 7 arguments. Since some of this arguments are booleans, a call to getMock() can get very obscure if you don't memorize the meaning of all the 7 arguments. Fortunately, the majority of them are optional, but to specify one of the last arguments you have to include, and care to hit the right default value, which changes with the parameter type. This leads to a classic call for obtaining a mock with an overridden constructor:

$this->getMock('My_Class', array(), array(), '', false);

Which can even get to:

$this->getMock('My_Class', array(), array(), '', false, false, false);

Or in case you actually want to specify additional behavior, to:

$this->getMock('My_Class', array('doSomething', 'doSomethingElse'), array('someParam', 42), '', true, false);

The Builder creational pattern is a small layer of abstraction over the instantation process, that in this case gives you a clear Api:

$this->getMockBuilder('My_Class')
     ->disableOriginalConstructor()
     ->getMock();

I hope this syntactic sugar would help you clean up your test suite, which should have the same rights and attention of your production code.

Examples

I wrote up a sample test case which uses PHPUnit 3.5 new features, so that you can quickly grasp the Api and keep it as a reference to upgrade your test suite.

<?php
class NewFunctionalities extends PHPUnit_Framework_TestCase
{
    /**
     * Some quick assertions on variables.
     */
    public function testNewAssertions()
    {
        $this->assertEmpty(null);
        $this->assertEmpty(0);
        $this->assertNotEmpty(42);
    }

    /**
     * Some more sophisticated assertions on objects fields.
     */
    public function testNewAssertionsOnObjectsAttributes()
    {
        $car = new Car;
        $this->assertAttributeEmpty('wheels', $car);

        $car->wheels = 4;
        $this->assertAttributeNotEmpty('wheels', $car);
    }
    
    /**
     * If you have ever written $this->assertTrue($object instanceof My_Class),
     * you'll appreciate this.
     * I only wish PHP allowed classes and interfaces to be passed like in Java:
     * $this->assertInstanceOf(Countable.class, $car)
     * to catch undefined classes issues.
     */
    public function testNewAssertionsOnObjects()
    {
        $car = new Car();
        $this->assertInstanceOf('Car', $car);
        $this->assertNotInstanceOf('Countable', $car);
    }

    /**
     * Simplified type checks.
     */
    public function testNewAssertionsOnScalars()
    {
        $string = 'ElePHPants are cute';
        $this->assertInternalType('string', $string);
        $this->assertNotInternalType('int', $string);
    }

    /**
     * Builder pattern for mocks.
     * Other methods on MockBuilder: setConstructorArgs(), setMockClassName(),
     *                               disableOriginalClone(), disableAutoload()
     */
    public function testMockBuilder()
    {
        $busMock = $this->getMockBuilder('Bus')
                        ->setMethods(array('brake', 'steer'))
                        ->disableOriginalConstructor()
                        ->getMock();
        $this->assertInstanceOf('Bus', $busMock);
    }

    /**
     * Annotations to expand declarative exception checking.
     * Error conditions are usually a neglected part of test cases.
     *
     * @expectedException CustomException
     * @expectedExceptionMessage Trying out new features
     * @expectedExceptionCode 42
     */
    public function testExceptions()
    {
        throw new CustomException("Trying out new features", 42);
    }
}

class Car
{
    public $wheels;
    public function brake() {}
    public function steer($direction) {}
}

class Bus
{
    private $_driver; 

    public function __construct(Driver $driver)
    {
        $this->_driver = $driver;
    }

    public function brake() {}
    public function steer($direction) {}
}

class CustomException extends Exception {}
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.)