Given the following method:
public function foo($callback) {
    call_user_func($callback);
}
How would I test that the callback actually got called, using PHPUnit?  The foo() method has no return value.  Its only job is to execute a callback given to it, with some other lookups and misc. processing that I've left out for simplicity's sake.
I tried something like this:
public method testFoo() {
    $test = $this;
    $this->obj->foo(function() use ($test) {
        $test->pass();
    });
    $this->fail();
}
...but apparently there's no pass() method, so this doesn't work.
To test if something was invoked or not you need to create a mock test double and configure it to expect to be called N number of times.
Here's a solution for using an object callback (untested):
public method testFoo() {
  $test = $this;
  $mock = $this->getMock('stdClass', array('myCallBack'));
  $mock->expects($this->once())
    ->method('myCallBack')
    ->will($this->returnValue(true));
  $this->obj->foo(array($mock, 'myCallBack'));
}
PHPUnit will automatically fail the test if $mock->myCallBack() is never invoked, or invoked more than once.
I used stdClass and its method myCallBack() because I'm not sure if you can mock global functions like the one in your example. I might be wrong about that. 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With