phpunit mock - 方法不存在

phpunit mock - method does not exist

我最近在一个基于 CakePhp 3.x 的应用程序的 IntegrationTestCase 中将 PHPunit 从 5.3 更新到 5.5。而且我不明白如何更新我的模拟生成脚本。

最初我是这样创建我的模拟的:

$stub = $this->getMock('SomeClass', array('execute'));
$stub->method('execute')
     ->will($this->returnValue($this->returnUrl));

更改为 PHPUnit 5.5 后,我收到以下警告:

PHPUnit_Framework_TestCase::getMock() is deprecated,
use PHPUnit_Framework_TestCase::createMock()
or PHPUnit_Framework_TestCase::getMockBuilder() instead

为了修复此警告,我将模拟生成更改为:

$stub = $this->getMockBuilder('SomeClass', array('execute'))->getMock();
$stub->method('execute')
     ->will($this->returnValue($this->returnUrl));```

现在我在 运行 测试时收到以下错误消息:

exception 'PHPUnit_Framework_MockObject_RuntimeException' 
with message 'Trying to configure method "execute" which cannot be
configured because it does not exist, has not been specified, 
is final, or is static'

任何人都知道,如何避免这个错误?谢谢。

PHPUnit_Framework_TestCase::getMockBuilder() 只接受一 (1) 个参数,即 class 名称。模拟的方法是通过返回的模拟构建器对象 setMethods() 方法来定义的。

$stub = $this
    ->getMockBuilder('SomeClass')
    ->setMethods(['execute'])
    ->getMock();

另见

首先,只是

$stub = $this->getMockBuilder('SomeClass')->getMock();

其次,错误指出方法 execute 确实存在于您的 class SomeClass.

所以,检查它是否真的存在,它是 public 而不是 final

如果一切正常,请检查完整的 class名称,如果它是真实的并且指定了正确的命名空间。

为了避免 classname 出现愚蠢的错误,最好使用以下语法:

$stub = $this->getMockBuilder(SomeClass::class)->getMock();

在这种情况下,如果 SomeClass 不存在或缺少命名空间,您将收到关于它的明确错误。

当我再次遇到这个问题时,我会把这个作为自己的答案:

模拟的方法可能不是私有的。

也许,您模拟的 class 中不存在该方法。

对上层消息的补充:拆分 mock 方法声明

而不是这个:

$mock
    ->method('persist')
       ->with($this->isInstanceOf(Bucket::class))
       ->willReturnSelf()
    ->method('save')
       ->willReturnSelf()
;

使用这个:

$mock
    ->method('persist')
        ->willReturnSelf()
;

$mock
   ->method('save')
       ->willReturnSelf()
;