【问题标题】:MockBuilder doesn't see method in InterfaceMockBuilder 在接口中看不到方法
【发布时间】:2021-10-27 04:59:55
【问题描述】:

我正在尝试模拟 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

我做错了什么?

【问题讨论】:

    标签: php mocking phpunit


    【解决方案1】:

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

    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());
            }
        }
    }
    

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

    【讨论】:

      【解决方案2】:

      Throwable::getPrevious() 要么是最终的要么是静态的,所以你不能模拟它。

      如果您使用 final 方法创建一个类并尝试模拟它,您将收到相同的错误消息。

      class Foo {
        final public function say()
        {
      
        }
      }
      
      $throwableMock = $this->getMockBuilder(Foo::class)
                                    ->getMock();
      
      $throwableMock->method('say')
                    ->willReturn('xxx');
      
      // Trying to configure method "say" which cannot be configured because it does not exist, has not been specified, is final, or is static
      

      所以你应该模拟具体的Exception 类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-30
        • 1970-01-01
        • 2013-07-28
        • 2017-10-24
        • 1970-01-01
        • 1970-01-01
        • 2010-12-14
        相关资源
        最近更新 更多