phpspec / prophecy

Highly opinionated mocking framework for PHP 5.3+
MIT License
8.53k stars 242 forks source link

Support for mocking methods with "static" return type #620

Closed aik099 closed 3 months ago

aik099 commented 7 months ago

When attempting to mock a method with a static return type (see https://php.watch/versions/8.0/static-return-type), then you'll get this error:

Prophecy\Exception\Prophecy\MethodProphecyException: Cannot create a return value for the method as the type "static" is not supported. Configure an explicit return value instead.

Code:

class Process implements \IteratorAggregate
{
    public function mustRun(?callable $callback = null, array $env = []): static
    {
        return $this;
    }
}
stof commented 3 months ago

The error message does not say that mocking such methods is not supported. It says that guessing a return value is not supported and you need to configure an explicit one (for instance by using ->willReturnSelf())

aik099 commented 3 months ago

The error message does not say that mocking such methods is not supported. It says that guessing a return value is not supported and you need to configure an explicit one (for instance by using ->willReturnSelf())

That helped. Thanks.

What about the associated PR ( https://github.com/phpspec/prophecy/pull/621 ) to improve guessing code?

aik099 commented 3 months ago

I'm getting an error, that willReturnSelf method isn't defined in the used Prophecy version. I've used this code instead:

$mock = $this->prophesize('Process');
$mock->mustRun()->willReturn($mock)->shouldBeCalled();

is this correct way or I should be doing

$mock = $this->prophesize('Process');
$mock->mustRun()->willReturn($mock->reveal())->shouldBeCalled();

instead?

stof commented 3 months ago

ah indeed. We don't have willReturnSelf in Prophecy (maybe I confused with PHPUnit mock or with a past discussion on Prophecy that has not been implemented).

The first code snippet is fine. ->willReturn does not require revealing explicitly.

aik099 commented 3 months ago

Great. Closing.