Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

can't stub getMessage method of interface that extends Throwable #4458

Closed
jacekkarczmarczyk opened this issue Sep 18, 2020 · 1 comment
Closed
Labels
feature/test-doubles Test Stubs and Mock Objects type/bug Something is broken

Comments

@jacekkarczmarczyk
Copy link

Q A
PHPUnit version 9.3.10
PHP version 7.4
Installation Method Composer

Summary

$mock->method('getMessage') fails for interface that extends Throwable

Current behavior

testRealThrowable fails with error:

Trying to configure method "getMessage" which cannot be configured because it does not exist, has not been specified, is final, or is static

How to reproduce

<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;
use Throwable;

interface Bar extends Throwable
{
    public function foo();
}

interface FakeThrowable
{
    public function getMessage();
}

interface Baz extends FakeThrowable
{
    public function foo();
}

final class FooTest extends TestCase
{
    public function testFakeThrowable(): void
    {
        $mock = $this->createMock(Baz::class);
        $mock->method('foo')->willReturn(null);
        $mock->method('getMessage')->willReturn(null);
        $this->assertTrue(true);
    }

    public function testRealThrowable(): void
    {
        $mock = $this->createMock(Bar::class);
        $mock->method('foo')->willReturn(null);
        $mock->method('getMessage')->willReturn(null);
        $this->assertTrue(true);
    }
}

Expected behavior

Both tests pass

@jacekkarczmarczyk jacekkarczmarczyk added the type/bug Something is broken label Sep 18, 2020
@sebastianbergmann sebastianbergmann added the feature/test-doubles Test Stubs and Mock Objects label Sep 18, 2020
@thicolares
Copy link

@jacekkarczmarczyk: it happens because when PHPUnit detects you're mocking an interface that extends Throwable, PHPUnit returns an Exception mock instead [1].

But on Exception, getMessage is final therefore you see the error.

[1] You may want to read this thread that was created based on this bug report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature/test-doubles Test Stubs and Mock Objects type/bug Something is broken
Projects
None yet
Development

No branches or pull requests

3 participants