-
Notifications
You must be signed in to change notification settings - Fork 28
Mock object
This is a tutorial for using https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/MockObject.
UPDATE: PHPUnit 3.6 will have $this->returnValueMap()
. Please check that out.
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