我最近在一个CakePhp 3应用的IntegrationTestCase中将PHPunit从5.3更新到5.5。基于x。我不知道如何更新我的模拟生成脚本。
最初我是这样创建mock的:
$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)参数,即类名。要模拟的方法可以通过返回的模拟构建器对象setMethods()
方法来定义。
$stub = $this
->getMockBuilder('SomeClass')
->setMethods(['execute'])
->getMock();
参见
- PHPUnit Manual> Test double> Mock Objects
当我再次遇到这个问题时,我会把这个问题留给自己:
模拟的方法不能是私有的
首先,它只是
$stub = $this->getMockBuilder('SomeClass')->getMock();
第二,错误表明方法execute
确实存在于您的类SomeClass
中。
那么,检查它是否真的存在并且它是public
而不是final
。
如果一切正常,检查一个完整的类名,如果它是真实的并且指定了正确的命名空间。
为了避免在classname上出现愚蠢的错误,最好使用以下语法:
$stub = $this->getMockBuilder(SomeClass::class)->getMock();
在这种情况下,如果someeclass不存在或名称空间缺失,您将得到一个明确的错误。
上层消息:拆分模拟方法声明
而不是:
$mock
->method('persist')
->with($this->isInstanceOf(Bucket::class))
->willReturnSelf()
->method('save')
->willReturnSelf()
;
使用:
$mock
->method('persist')
->willReturnSelf()
;
$mock
->method('save')
->willReturnSelf()
;
也许,该方法不存在于您所模拟的类中。