The previous test was a great example for how you can make multiple stubs for a single method however in reality it
is not the best way for that particular test to be written. What if the Item objects in an
ItemGroup aren't stored in the order they were passed in? I am needlessly binding my test
to the order objects are stored. Phake provides the ability to map multiple answers to the same stub. This is done
simply by chaining the answers together. I could rewrite the test from the previous chapter to utilize this feature
of Phake.
Example 2.11.
<?php class ItemGroupTest extends PHPUnit_Framework_TestCase { private $itemGroup; private $item1; private $item2; private $item3; public function setUp() { $this->item1 = Phake::mock('Item'); $this->item2 = Phake::mock('Item'); $this->item3 = Phake::mock('Item'); $this->itemGroup = new ItemGroup(array($this->item1, $this->item2, $this->item3)); } public function testAddItemsToCart() { $cart = Phake::mock('ShoppingCart'); Phake::when($cart)->addItem(Phake::anyParameters())->thenReturn(10) ->thenReturn(20) ->thenReturn(30); $totalCost = $this->itemGroup->addItemsToCart($cart); $this->assertEquals(30, $totalCost); } } ?>
You will notice a few of differences with Example 2.10, “”
and Example 2.11, “”. The first difference is that there
is only one call to Phake::when(). The second difference is that I have chained together three
calls to thenReturn(). The third difference is instead of passing one of my mock Item
objects I have passed the result of the Phake::anyParameters() method. This is a special argument
matcher in Phake that essentially says match any call to the method regardless of the number of parameters or the
value of those parameters.
So, this single call to Phake::when() is saying: "Whenever a call to $cart->addItem()
is made, regardless of the parameters, return 10 for the first call, 20 for the second call, and 30 for the third
call." If you are using consecutive call stubbing and you call the method more times than you have answers set, the
last answer will continue to be returned. In this example, if $cart->addItem() were called a fourth
time, then 30 would be returned again.