7

Using PHPUnit, I wonder how we can have multiple expectation from the same stub/mock.

For example, I want to test that the mock will have the method display() called and return NULL. I also want to test that the method process() will be called.

In fact my test is called testProcessIsCalledIfDisplayReturnNull().

So I need to setup 2 expectations on the same mock object, and the manual doesn't really help about that :(

elitalon
  • 9,191
  • 10
  • 50
  • 86
FMaz008
  • 11,161
  • 19
  • 68
  • 100

2 Answers2

10

If you know, that method is called once use $this->once() in expects(), otherwise use $this->any()

$mock = $this->getMock('nameOfTheClass', array('firstMethod','secondMethod','thirdMethod'));
$mock->expects($this->once())
     ->method('firstMethod')
     ->will($this->returnValue('value'));
$mock->expects($this->once())
     ->method('secondMethod')
     ->will($this->returnValue('value'));
$mock->expects($this->once())
     ->method('thirdMethod')
     ->will($this->returnValue('value'));
  • As I understand it once() should only be used when it's considered important that the method is called exactly once - when code that called the method more or less than once should be considered broken. If the current implementation calls it once, but it would be fine to change it to zero or more in future then use any(). That makes it easier to change the code in future. – bdsl Jun 02 '17 at 19:28
6

I've tried this, and it seems to works as long as the call order stays good:

$mock = $this->getMock('mockWorker', array('display', 'process'));
$mock->expects($this->exactly(1))
     ->method('display')
     ->will($this->returnValue(null));
$mock->expects($this->exactly(1))
     ->method('process');
Paul DelRe
  • 4,003
  • 1
  • 24
  • 26
FMaz008
  • 11,161
  • 19
  • 68
  • 100
  • 4
    You can use `once()` instead of `exactly(1)`. Keep in mind that this doesn't create an ordering between the two expectations, but it's usually good enough. If you require specific ordering, use `at($index)`. – David Harkness Apr 29 '11 at 17:36