如何使用PHPUnit测试Doctrine Cache代码

时间:2014-01-09 20:45:36

标签: php symfony phpunit

我在我的系统中使用Doctrine APCu Cache,虽然它在开发和生产中都很完美,但是当我运行PHPUnit来测试应用程序时,编码的代码行中的缓存系统永远不会被标记为已测试。

Doctrine APC缓存服务配置:

# Services
services:
    doctrine.common.cache:
        class: Doctrine\Common\Cache\ApcCache

标记为未经测试的代码:

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缓存?

1 个答案:

答案 0 :(得分:4)

您需要以某种方式模拟$this->cache对象以始终在fetch方法上返回true。请参阅文档here

在你的测试中看起来像这样:

// 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引用你的模拟对象,而不是普通的缓存对象)。

相关问题