23

This came up trying to write a test for a method of a class that calls a mock method with a closure. How would you verify the closure being called?

I know that you would be able to assert that the parameter is an instance of Closure. But how would you check anything about the closure?

For example how would you verify the function that is passed:

 class SUT {
     public function foo($bar) {
         $someFunction = function() { echo "I am an anonymous function"; };
         $bar->baz($someFunction);
     }
 }

 class SUTTest extends PHPUnit_Framework_TestCase {
     public function testFoo() {
         $mockBar = $this->getMockBuilder('Bar')
              ->setMethods(array('baz'))
              ->getMock();
         $mockBar->expects($this->once())
              ->method('baz')
              ->with( /** WHAT WOULD I ASSERT HERE? **/);

         $sut = new SUT();

         $sut->foo($mockBar);
     }
 }

You can't compare two closures in PHP. Is there a way in PHPUnit to execute the parameter passed in or in some way verify it?

3 Answers 3

19

If you want to mock an anonymous function (callback) you can mock a class with __invoke method. For example:

$shouldBeCalled = $this->getMock(\stdClass::class, ['__invoke']);
$shouldBeCalled->expects($this->once())
    ->method('__invoke');

$someServiceYouAreTesting->testedMethod($shouldBeCalled);

If you are using latest PHPUnit, you would have to use mock builder to do the trick:

$shouldBeCalled = $this->getMockBuilder(\stdClass::class)
    ->setMethods(['__invoke'])
    ->getMock();

$shouldBeCalled->expects($this->once())
    ->method('__invoke');

$someServiceYouAreTesting->testedMethod($shouldBeCalled);

You can also set expectations for method arguments or set a returning value, just the same way you would do it for any other method:

$shouldBeCalled->expects($this->once())
    ->method('__invoke')
    ->with($this->equalTo(5))
    ->willReturn(15);
3
  • great answer! I've wanted to know how to do this for a while now.
    – Reactgular
    Mar 11, 2017 at 0:51
  • Not only does this work, but is_callable($shouldBeCalled) returns true as well.
    – Reactgular
    Mar 11, 2017 at 0:56
  • Clever! It does not work for callback that take references, though.
    – Tgr
    Jan 7, 2019 at 7:58
9

Your problem is that you aren't injecting your dependency (the closure), which always makes unit testing harder, and can make isolation impossible.

Inject the closure into SUT::foo() instead of creating it inside there and you'll find testing much easier.

Here is how I would design the method (bearing in mind that I know nothing about your real code, so this may or may not be practical for you):

class SUT 
{
    public function foo($bar, $someFunction) 
    {
        $bar->baz($someFunction);
    }
}

class SUTTest extends PHPUnit_Framework_TestCase 
{
    public function testFoo() 
    {
        $someFunction = function() {};

        $mockBar = $this->getMockBuilder('Bar')
             ->setMethods(array('baz'))
             ->getMock();
        $mockBar->expects($this->once())
             ->method('baz')
             ->with($someFunction);

        $sut = new SUT();

        $sut->foo($mockBar, $someFunction);
    }
}
7
  • Ok, so you suggest we do something like $someFunction = function() { echo "I am an anonymous function"; }; $sut = new SUT(); $sut->foo($bar, $someFunction);. How do we test it there? My point is, the anonymous function has to be defined somewhere. You can pass it up the call stack all you want, but eventually it has to be defined. So how do you test it?
    – Travesty3
    Oct 8, 2013 at 19:35
  • @Travesty3: My answer contained the rewritten test showing you exactly how to test it. You test it just like you would anything else that uses injected dependencies - you mock the dependency and inject the mock.
    – FtDRbwLXw6
    Oct 8, 2013 at 19:39
  • @Travesty3 You can have a factory class that returns the closures then you would be able to test the logic of the closure in isolation
    – Schleis
    Oct 8, 2013 at 19:39
  • @drrcknlsn: You're showing how to test the SUT::foo() method with the anonymous function mocked, but not how to test the anonymous function. What I mean is, how do you verify that "I am an anonymous function" gets echoed?
    – Travesty3
    Oct 8, 2013 at 19:41
  • @Travesty3: The job of SUTTest::testFoo() is to verify that SUT::foo() behaves as expected. According to your pasted code, SUT::foo()'s only job is to call the function. The test in my answer verifies that the function is called, and so it has verified that SUT::foo() behaves as expected. If you need to test the function itself, then you can do so in another test suite dedicated to doing so. Provide it known good/bad inputs and verify the outputs (or side effects, as relevant).
    – FtDRbwLXw6
    Oct 8, 2013 at 19:49
9

If the closure has some side effects inside SUT that could be verified by the test after the mock invocation, use returnCallback to provide another closure to be called with the passed arguments and have its return value returned to SUT. This will allow you to call SUT's closure to cause the side effects.

 class SUT {
     public function foo($bar) {
         $someFunction = function() { return 5 * 3; };
         return $bar->baz($someFunction);
     }
 }

 class SUTTest extends PHPUnit_Framework_TestCase {
     public function testFoo() {
         $mockBar = $this->getMockBuilder('Bar')
              ->setMethods(array('baz'))
              ->getMock();
         $mockBar->expects($this->once())
              ->method('baz')
              ->will($this->returnCallback(function ($someFunction) {
                  return $someFunction();
              }));

         $sut = new SUT();

         self::assertEquals(15, $sut->foo($mockBar));
     }
 }

Your Answer

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

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