Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit - How to test if callback gets called?

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.

like image 666
FtDRbwLXw6 Avatar asked Feb 15 '12 15:02

FtDRbwLXw6


1 Answers

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.

like image 63
Mike B Avatar answered Oct 12 '22 14:10

Mike B