【发布时间】:2017-11-24 19:00:54
【问题描述】:
我正在尝试找到一种方法来检查传递给我的单元测试中的方法的闭包函数是否被准确地调用了一次。但是 PHP 中的 Closure 类被声明为 final,当我运行它时我收到以下错误消息:“Class "Closure" is declared "final" and cannot be mocked."
这是一个代码示例。我正在尝试检查 valueProducer() 是否被调用了一次。
class PoorCache{
protected $storage;
/**
* Returns value from cache and if the value lacks puts it into the cache storage
* @param string $key
* @param Closure $valueProducer produces a value for storage, i.e. makes a request to DB
* @return mixed
*/
public function remember($key, Closure $valueProducer)
{
if (array_key_exists($key, $this->storage))
{
return $this->storage[$key];
}
$this->storage[$key] = $valueProducer();
return $this->storage[$key];
}
}
class PoorCacheTest extends TestCase {
public function testRemeber(){
$mockedValueProducer = $this->getMock(\Closure::class);
$mockedValueProducer->expects($this->once())->method('call');
$cache = new PoorCache();
$cache->remember('myKey', $mockedValueProducer);
$cache->remember('myKey', $mockedValueProducer);
}
}
【问题讨论】:
-
我不知道
Closure是final,很有趣。您可以尝试的一件事是删除Closure类型提示,并在该方法的开头添加基于!is_callable()之类的PHP 测试。您必须尝试模拟类如何变得可调用(可能是对实现调用魔法的东西的部分模拟?必须在这里玩......) -
感谢您的回答。从方法规范中删除闭包肯定会解决问题。但它是一个旁路。我想知道是否有人知道简单的解决方案。
标签: php unit-testing testing mocking