5

With PHPUnit, I am testing a sequence of method calls using ->at(), like so:

$mock->expects($this->at(0))->method('execute')->will($this->returnValue('foo'));
$mock->expects($this->at(1))->method('execute')->will($this->returnValue('bar'));
$mock->expects($this->at(2))->method('execute')->will($this->returnValue('baz'));

How can I set up the mock so that, in the above scenario, if execute() is called four or more times, it will immediately fail? I tried this:

$mock->expects($this->at(3))->method('execute')->will($this->throwException(new Exception('Called too many times.')));

But this also fails if execute() is not called four times. It needs to fail immediately, otherwise the system under test will produce errors of its own, which causes the resulting error message to be unclear.

4 Answers 4

11

I managed to find a solution in the end. I used a comination of $this->returnCallback() and passing the PHPUnit matcher to keep track of the invocation count. You can then throw a PHPUnit exception so that you get nice output too:

$matcher = $this->any();
$mock
    ->expects($matcher)
    ->method('execute')
    ->will($this->returnCallback(function() use($matcher) {
        switch ($matcher->getInvocationCount())
        {
            case 0: return 'foo';
            case 1: return 'bar';
            case 2: return 'baz';
        }

        throw new PHPUnit_Framework_ExpectationFailedException('Called too many times.');
    }))
;
2
  • Minor fix: invocation number starts from 1, not 0
    – ox160d05d
    Commented May 21, 2020 at 22:19
  • The function passed to returnCallback also accepts a function whose parameters are the same as parameters as the mocked method as well.
    – tschumann
    Commented Oct 14, 2022 at 0:19
3

For special cases like this, I typically use something like the following:

public function myMockCallback() {
     ++$this -> _myCounter;
     if( $this -> _myCounter > 3 ) {
          // THROW EXCEPTION OR TRIGGER ERROR
     }
     ... THEN YOUR CASE STATEMENT OR IF/ELSE WITH YOUR CHOICE OF RETURN VALUES
} 

... INSIDE TEST FUNCTION ....

$mockObject ->expects($this->any())
            ->method('myMethod')
            ->will($this->returnCallback( array ($this, 'myMockCallback' )));
3
  • I always have a hard time finding things like these in the documentation (scrolling...scrolling) but I also found an example here as well too: phpunit.de/manual/current/en/… See Example 11.5: Stubbing a method call to return a value from a callback Hope this helps!
    – Gary
    Commented Jun 8, 2011 at 2:30
  • 1
    Thanks! This is very similar to what I ended up doing. I would have posted the solution already, but I don't have enough reputation to answer my own question :( The one thing I did differently was to take the object returned by $this->any() (a 'matcher') and pass it to the callback via use(), because it actually keeps track how many times it has been invoked, and you can get this by calling a method (getInvocationCount() I think ).
    – ezzatron
    Commented Jun 8, 2011 at 4:50
  • neat, I'll have to check that out. Thanks!
    – Gary
    Commented Jun 8, 2011 at 16:12
2

You could separate test to 2 dependent methods, using @depends annotation.

In this case your first test only tests that there are exact 3 method executions, and second - other logic.

2
  • Interesting answer. In this case I'm actually trying to write a helper method that will return a mock with all of these expectations set up dynamically based upon a sequence represented as an array. It needs to be dead simple as I'll be re-using it a lot, so writing two tests for each sequence I'm testing would be a bit too cumbersome unfortunately.
    – ezzatron
    Commented Jun 8, 2011 at 1:09
  • @Ezzatron: yep. And iirc second test method will not be called if the first one (the "helper" one) has failed. Well, have no another ideas if this is not suitable for you...
    – zerkms
    Commented Jun 8, 2011 at 1:11
0

What about using data providers?

class MyTest extends PHPUnit.... { 
    /** 
     * @var const how much till throwing exception 
    */
    const MAX_EXECUTE_TILL_EXCEPTION = 3; 

    public function setUp(){} 

    public function tearDown(){} 

    /**
     *  @dataProvider MyExecuteProvider  
    */
    pulbic function testMyExecuteReturnFalse($data){
        $mock = //setup your mock here

        //if using "$ret" doesn't work you cant just call another private helper that will decide if you need to 
        //  return value or throwing exception 
        if (self::MAX_EXECUTE_TILL_EXCEPTION == $data){ 
            $ret = $this->throwException(new Exception('Called too many times.'));
        } else {
            $ret = $this->returnValue('foo'); 
        } 
        $mock->expects($this->at($data))->method('execute')->will($ret);
    }

    public function MyExecuteProvider(){
            return array(
            0,1,2,3
        )
    }
}

This is just another idea, and I think that zerkms suggested very good idea as well

1
  • I don't think that would work. I'm trying to test a sequence of calls, not a single call at a particular index. Thanks for the input though.
    – ezzatron
    Commented Jun 8, 2011 at 4:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.