我在我的系统中使用了Doctrine APCu Cache,尽管它在开发和生产中都运行良好,但当我运行PHPUnit来测试应用程序时,编码缓存系统的代码行永远不会被标记为已测试。
原则 APC 缓存服务配置:
# Services
services:
doctrine.common.cache:
class: DoctrineCommonCacheApcCache
标记为未经测试的代码:
public function findActiveStatus($cache = true)
{
if (($cache) && ($statusList = $this->cache->fetch('sys_active_status'))) {
return unserialize($statusList); // non-tested
} else {
$statusList = $this->findAllStatus();
$this->cache->save(
'sys_active_status',
serialize($statusList)
);
return $statusList;
}
}
我已经做了多个请求和操作来测试这个函数,但 PHPUnit 从未将这一行标记为测试。
未经证实的代码行是数字 3:return unserialize($statusList);
有谁知道如何用PHPUnit测试Doctrine Cache?
您需要以某种方式模拟$this->cache
对象,以始终在 fetch 方法上返回 true。 请参阅此处的文档。
在您的测试中,它看起来像这样:
// Replace 'Cache' with the actual name of the class you are trying to mock
$cacheMock = $this->getMock('Cache', array('fetch'));
$cacheMock->expects($this->once())
->method('fetch')
->will($this->returnValue('some return value'));
第二行基本上是说我希望调用一次 fetch 方法,当我这样做时,我希望你无论如何都返回值some return value
。 如果没有发生这种情况(例如,根本不调用 fetch 方法,或者多次调用),PHPUnit 将无法通过测试。
一旦你被模拟了,你将需要以某种方式将缓存模拟注入到你正在测试的对象中(以便在你的对象中,$this->cache
指的是你的模拟对象,而不是普通的缓存对象)。