sebastianbergmann/phpunit-mock-objects

Prevent runtime type error due to wrong return value configuration

sebastianbergmann opened this issue · 2 comments

willReturn() should raise an error when a return value is configured that does not match the stubbed method's return value.

<?php declare(strict_types=1);

class C
{
    public function m(): int
    {
        return 1;
    }
}

final class Test extends PHPUnit\Framework\TestCase
{
    public function testOne(): void
    {
        $o = $this->createMock(C::class);
        
        $o->method('m')->willReturn('not an integer');
        
        $o->m();
    }
}

Actual: TypeError when stubbed method is invoked

PHPUnit 7.1-gfafd3c555 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 68 ms, Memory: 4.00MB

There was 1 error:

1) Test::testOne
TypeError: Return value of Mock_C_06141907::m() must be of the type integer, string returned

/home/sb/Test.php:19

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

This is possible if the mock object passes its own instance to Builder\InvocationMocker which allows the builder to find out the return type hint. But right now I'm not sure whether that has unexpected side effects nor if it's a «smart» solution. I'll spend some more time on this.

Update: I pushed this experiment to https://github.com/dnaber-de/phpunit-mock-objects/tree/issue-409-experimental