5

I was looking to get different return values for the same method while calling it multiple times. I tried many things but did not get an exact answer for this.

$mock = $this->getMockBuilder('Test')
                ->disableOriginalConstructor()
                ->setMethods(array('testMethod'))
                ->getMock();
$mock->expects($this->once())->method('testMethod')->will($this->returnValue(true));
$mock->expects($this->second())->method('testMethod')->will($this->returnValue(false));

2 Answers 2

14

You can use willReturnOnConsecutiveCalls method

$mock
    ->expects($this->exactly(2))
    ->method('testMethod')
    ->willReturnOnConsecutiveCalls(true, false);

Alternative (for phpunit < 4):

$mock
    ->expects($this->exactly(2))
    ->method('testMethod')
    ->will($this->onConsecutiveCalls(true, false));
Sign up to request clarification or add additional context in comments.

1 Comment

Checking the source code, it looks like willReturn() can also handle multiple arguments to allow for consecutive calls.
4

I found this link which helps me to get it done using at($index) method. It returns a matcher that matches when the method it is evaluated for is invoked at the given $index.

The $index parameter for the at() matcher refers to the index, starting at zero, in all method invocations for a given mock object. Exercise caution when using this matcher as it can lead to brittle tests which are too closely tied to specific implementation details. More Details

$mock = $this->getMockBuilder('Test')
                ->disableOriginalConstructor()
                ->setMethods(array('testMethod'))
                ->getMock();
$mock->expects($this->at(0))->method('testMethod')->will($this->returnValue(true));
$mock->expects($this->at(1))->method('testMethod')->will($this->returnValue(false));

3 Comments

Great trick if you receive the expectations in an array. You can loop the array and iterate on adding each expectation.
@XaviMontero I used at here because the method was being multiple time in a loop so I want to return a different result on the index when the function was called.
n.b. at() is deprecated in PHPUnit 9 and will be removed in version 10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.