Skip to content

Mock object

elblinkin edited this page Dec 21, 2011 · 10 revisions

This is a tutorial for using https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/MockObject.

PHPUnit_Extensions_MockObject_Stub_ReturnMapping


UPDATE: PHPUnit 3.6 will have $this->returnValueMap(). Please check that out. It appears to support only $this->equalTo() usages of this extension.

Sometimes it is ideal to stub a method such that the return corresponds to the parameter list.

Previous to this extension there were two work-arounds:

Bad Solution #1 Use $this->at()

Example:

$mock
    ->expects($this->at(0))
    ->method("myMethod")
    ->with('foo')
    ->will($this->returnValue(0));

$mock
    ->expects($this->at(1))
    ->method("myMethod")
    ->with('bar')
    ->will($this->returnValue(1));

but this solution requires enforcing a strict invocation order which will lead to a very brittle test.

Bad Solution #2 Use $this->returnCallback()

Example:

    $mock
        ->expects($this->any())
        ->method('myMethod')
        ->with($this->anything())
        ->will($this->returnCallback($this, 'myMethodReturn'));
    
public function myMethodReturn($arg) {
    $returnVals = array(
        'foo' => 0,
        'bar => 1,
    );
    return $retVals[$arg];
}

but this solution can lead to un-tested logic growing inside your test code.

This extensions provides a solution that is less brittle than using $this->at() and removes the risk of growing logic in an arbitrary callback as with $this->returnCallback().

Example:

$returnMapBuilder = new PHPUnit_Extensions_MockObject_Stub_ReturnMapping_Builder();
$returnMapBuilder->addEntry()
    ->with(array('foo'))
    ->will($this->returnValue(0));
$returnMapBuilder->addEntry()
    ->with(array('bar'))
    ->will($this->returnValue(1));

$mock
    ->expects($this->any())
    ->method('myMethod')
    ->with($this->anything())    // ReturnMapping will take care of comparing
    ->will($returnMapBuilder->build());

->with() takes an array of PHPUnit_Framework_Constraints

->will() takes a single PHPUnit_Framework_MockObject_Stub

More Examples: https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/MockObject/Stub/ReturnMappingTest.php

New in v0.2.1

You can now specify a default return stub.

$returnMapBuilder = new PHPUnit_Extensions_MockObject_Stub_ReturnMapping_Builder();
    ->setDefault($this->returnValue('default'));

UPDATE: PHPUnit 3.6 will have $this->returnValueMap(). Please check that out. It appears to support only $this->equalTo() usages of this extension.

Clone this wiki locally