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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…