Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: How to Mock Multiple Calls to the Same Method

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));
like image 513
TIGER Avatar asked Dec 14 '22 17:12

TIGER


1 Answers

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));
like image 81
Nikita U. Avatar answered Dec 18 '22 00:12

Nikita U.