In PHPUnit, how do I indicate different with() on successive calls to a mocked method?

james picture james · Apr 30, 2011 · Viewed 18.1k times · Source

I want to call my mocked method twice with different expected arguments. This doesn't work because expects($this->once()) will fail on the second call.

$mock->expects($this->once())
     ->method('foo')
     ->with('someValue');

$mock->expects($this->once())
     ->method('foo')
     ->with('anotherValue');

$mock->foo('someValue');
$mock->foo('anotherValue');

I have also tried:

$mock->expects($this->exactly(2))
     ->method('foo')
     ->with('someValue');

But how do I add a with() to match the second call?

Answer

David Harkness picture David Harkness · Apr 30, 2011

You need to use at():

$mock->expects($this->at(0))
     ->method('foo')
     ->with('someValue');

$mock->expects($this->at(1))
     ->method('foo')
     ->with('anotherValue');

$mock->foo('someValue');
$mock->foo('anotherValue');

Note that the indexes passed to at() apply across all method calls to the same mock object. If the second method call was to bar() you would not change the argument to at().