Testing a system is often a complex task, due to so many involved dependencies. For example, it might happen that a bug of a dependency raises an issue where really it doesn't exist, because a component has a wrong reaction to a given stimulus.  This implies that the Bug Discovery is a time-consuming task, often preventing a fast problem fixing.

The "Stub" of a dependency is the operation of replacing it by a dummy representation: it may be an object behaving in a completely determined way, if inserted as a component of the System Under Test.    In this way, you can check the behavior of a given system part, as it has no dependencies at all on other definitions, that is its behavior can be verified no matter of any other component.  

PHPUnit allows an easy design of Stub objects. By way of example, let's suppose you have an object wrap executing the sum of two numbers. If you want to replace the real system executing sums, you simply have to ask for an easily controlled representation of that object: 

<?php

// tests/SumWrapTest.php
class SumWrapTest extends PHPUnit_Framework_TestCase
{
    public function testStub()
    {
        $sut = new SumWrap();

        //Create a stub for the Sum class.
        $stub = $this->getMock('Sum');

        //Configure the stub.
        $stub->expects($this->any())
             ->method('add')
             ->will($this->returnValue(2));

        $sut->setStrategy($stub);

        $this->assertEquals(2, $sut->compute(1, 1));
    }
}

The "getMock" method, provided by the Testing framework, generates a new Stub; then you can check the result of "add" method by an explicit definition of the result, via the following tools:  “will”, “expects” and “methods”. 

This latter allows the indication of the method to be replaced by a new definition, while the "will" method states which result needs to be returned by the system. The "expects" method represents the expected behavior replacing the original one.  

If the input values can be matched with the definition, it is possible to replace the result, otherwise the real method will be involved in such operation. 

The generated stub completely replaces all the original methods, so that no unpredictable behavior remains in the system.  You must remember that, when replacing a method by an explicit input definition via the "exactly" or "At" methods, if an input can not be validated, the real method is used and not the dummy ones, as no behavior has been defined for the input not validated. That's why you usually do not give details of requests when defining a Stub for a dependency. This is usually done when you are replacing the method with a Spy.

Comments

comments powered by Disqus

cloudparty

Follow Us