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

PHPUnit 3.5: easier asserting and mocking

Giorgio Sironi user avatar by
Giorgio Sironi
·
Sep. 26, 10 · Interview
Like (0)
Save
Tweet
Share
15.35K Views

Join the DZone community and get the full member experience.

Join For Free
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 {}
PHPUnit

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Create Spider Chart With ReactJS
  • Is DevOps Dead?
  • What Is API-First?

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: