【发布时间】:2019-12-14 20:39:18
【问题描述】:
我正在为控制台命令编写测试。在命令中,我们对外部服务进行了 2 次单独的 api 调用,我可以很好地模拟它们。但是这两个外部调用都包含在Cache::remember 中。我希望能够在我的测试中模拟这两个缓存,但似乎无法弄清楚。我似乎只能嘲笑第一个。它们有不同的键。
例如,我的控制台命令有这样的东西(我已经为此简化了)
Cache::remember("key-1", (60 * 60) * 24, function () use ($variable) {
return $this->externalApiAdapter->makeApiCall($variable);
});
Cache::remember("key-2", (60 * 60) * 24, function () {
return $this->secondExternalApiAdapter->makeAnotherApiCall();
});
在我的测试中,我希望一个缓存返回null,另一个返回一个模拟对象。
这是第一个。
Cache::shouldReceive('remember')
->with('key-1', (60 * 60) * 24, \Closure::class)
->andReturn(null);
如果我把第二个放进去
$mockedObject = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);
Cache::shouldReceive('remember')
->with('key-2', (60 * 60) * 24, \Closure::class)
->andReturn((object)json_decode($mockedObject));
它仍然返回 null。
请问如何模拟第二个缓存。
【问题讨论】:
标签: php laravel caching mocking phpunit