| Q | A
| --------------------| ---------------
| PHPUnit version | 8.1
| PHP version | 7.x
| Installation Method | Composer / PHAR
Would you accept a PR to support mocking closure, to ease checking that one is called?
I.e : https://3v4l.org/Yaq5A
public function testClosureIsCalled()
{
$callback = function () {};
$this->assertClosureWillBeCalled($callback);
SomeBusiness:caller($callback);
}
I cannot promise acceptance of such a pull request but would, of course, consider it.
This is already possible by mocking __invoke() on stdClass:
public function testClosureIsCalled() : void
{
$closure = $this->createPartialMock(stdClass::class, ['__invoke']);
$closure->expects(
$this->exactly(2)
)->method('__invoke');
$closure();
$closure();
}
Unlike this workaround, the proposed API is not really flexible, however, it'd be nice if the workaround was formalized as a feature.
@morozov
The provided solution results in:
createPartialMock() called with method(s) __invoke that do not exist in stdClass. This will not be allowed in future versions of PHPUnit.
An API for this might be nice indeed!
After some experimentation there still seems to be a method which works:
$mock = $this
->getMockBuilder(\stdclass::class)
->addMethods(['__invoke'])
->getMock();
$mock
->expects(self::once())
->method('__invoke'));
(Tested on PHPUnit 9 / PHP 7.3)
Most helpful comment
This is already possible by mocking
__invoke()onstdClass:Unlike this workaround, the proposed API is not really flexible, however, it'd be nice if the workaround was formalized as a feature.