Skip to content
This repository has been archived by the owner on Feb 20, 2023. It is now read-only.

Prevent runtime type error due to wrong return value configuration #409

Closed
sebastianbergmann opened this issue Feb 20, 2018 · 2 comments
Closed

Comments

@sebastianbergmann
Copy link
Owner

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.
@dnaber-de
Copy link
Contributor

dnaber-de commented Apr 7, 2018

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

@sebastianbergmann
Copy link
Owner Author

Moved to sebastianbergmann/phpunit#3122.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants