I am using Doctrine APCu Cache in my system and, although it works perfectly in both development and production, when I run PHPUnit to test the app, the code lines where is coded the cache system never are marked as tested.
Doctrine APC Cache service config:
# Services
services:
doctrine.common.cache:
class: Doctrine\Common\Cache\ApcCache
Code marked as untested:
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;
}
}
I have done multiple requests and operations to test this function, but PHPUnit never mark as tested this line.
The line of code that is unproven is the number 3: return unserialize($statusList);
Does anyone know how to test the Doctrine Cache with PHPUnit?
You will need to somehow mock the $this->cache object to always return true on the fetch method. See the documentation here.
It would look something like this in your test:
// 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'));
The second line basically says I expect to call the fetch method once, and when I do I want you to return the value some return value back no matter what. If that doesn't happen (e.g., the fetch method isn't called at all, or called more than once), PHPUnit will fail the test.
Once you get it mocked, you will need to somehow inject the cache mock into the object you are testing (so that in your object, $this->cache refers to your mock object, and not the normal cache object).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With