Phpunit: Add support for stubbing and mocking closures

Created on 20 Feb 2019  路  4Comments  路  Source: sebastianbergmann/phpunit

| 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);
}
featurtest-doubles typenhancement

Most helpful comment

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.

All 4 comments

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)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

keradus picture keradus  路  4Comments

greg0ire picture greg0ire  路  4Comments

edyan picture edyan  路  4Comments

stephen-leavitt-sonyatv-com picture stephen-leavitt-sonyatv-com  路  4Comments

keradus picture keradus  路  3Comments