首页 > 解决方案 > MockBuilder 在接口中看不到方法

问题描述

我正在尝试模拟 Throwable 接口,但 MockBuilder 没有看到 getPrevious() 方法。

    $throwableMock = $this->getMockBuilder(\Throwable::class)
        ->disableOriginalConstructor()
        ->getMock();

    $throwableMock->method('getPrevious')
        ->willReturn($domainExceptionMock);

我收到此错误:

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

如果我将 addMethods 添加到模拟生成器,如下所示:

$throwableMock = $this->getMockBuilder(\Throwable::class)
        ->addMethods(['getPrevious'])
        ->disableOriginalConstructor()
        ->getMock();

我收到以下错误:

Trying to set mock method "getPrevious" with addMethods(), but it exists in class "Throwable". Use onlyMethods() for methods that exist in the class

我究竟做错了什么?

标签: phpmockingphpunit

解决方案


我不确定您要对模拟异常做什么,但您可能会发现构建一个真实对象更容易,然后抛出它:

class SanityTest extends TestCase
{
    public function testThrowingMock(): void
    {
        $domainExceptionMock = new \RuntimeException('hello');
        $exception = new \Exception('msg', 0, $domainExceptionMock);

        $tst = $this->createMock(Hello::class);  // class Hello {public function hello() {} }
        $tst->method('hello')
            ->willThrowException($exception);

        try {
            $tst->hello();
        } catch (\Exception $e) {
            $this->assertInstanceOf(\RuntimeException::class, $e->getPrevious());
        }
    }
}

模拟一切可能比设置和使用,和/或事后检查真实对象更困难。


推荐阅读