Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Different return values every call of mocked method

For example I have a mocked Class like below:

$mock= $this->getMockBuilder("SomeClass")->disableOriginalConstructor()->getMock();

$mock->expects($this->any())
     ->method("someMethod")
     ->will($this->returnValue("RETURN VALUE"));

The only param of someMethod is an array $arr.

What I want to do is to return $arr[0] when someMethod is called for the first time, $arr[1] for the second time and so on.

The size of $arr is dynamic.

Any idea how to achieve this if this is even possible?

like image 648
Rey Libutan Avatar asked Feb 04 '14 04:02

Rey Libutan


People also ask

Which method is used to create a mock with PHPUnit?

PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.

What is stub in PHPUnit?

We then use the Fluent Interface that PHPUnit provides to specify the behavior for the stub. In essence, this means that you do not need to create several temporary objects and wire them together afterwards. Instead, you chain method calls as shown in the example. This leads to more readable and “fluent” code.


1 Answers

$mock->expects($this->any())
    ->method("someMethod")
    ->will($this->onConsecutiveCalls(1, 2, 3));

With onConsecutiveCalls you can set a return value for every call of someMethod. The first call returns 1. The second call 2. The third call 3.

like image 158
SenseException Avatar answered Sep 18 '22 13:09

SenseException