我正在为控制台命令编写一个测试。在命令中,我们对外部服务进行了两个单独的api调用,我可以很好地模拟这两个调用。但这两个外部调用都包装在Cache::remember中。我希望能够在我的测试中模拟这两个缓存,但似乎无法弄清楚。我似乎只能嘲笑第一个。他们有不同的钥匙。
例如,我的控制台命令如下所示(我对this进行了简化)
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。
我怎样才能模拟第二个缓存呢?
发布于 2019-08-07 17:27:20
您可以使用->once()来实现这些目的。
// This will be returned the first time Cache::remember is called
Cache::shouldReceive('remember')
->once()
->with('key-1', (60 * 60) * 24, \Closure::class)
->andReturn(null);
$mockedObject = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);
// This will be returned the second time Cache::remember is called
Cache::shouldReceive('remember')
->once()
->with('key-2', (60 * 60) * 24, \Closure::class)
->andReturn((object)json_decode($mockedObject));发布于 2019-08-07 23:28:06
好吧,这是我有点傻,但在盯着代码和文档几个小时后,我发现了这一点。
在我的示例中,我不需要模拟缓存,因为缓存中的方法已经被模拟了。另外,我没有从Cache方法中返回任何值。
在我的命令中,Cache::remember块在它们自己的方法中,但是我没有返回任何东西。
所以这就是
public function methodOne ()
{
Cache::remember("key-1", (60 * 60) * 24, function () use ($variable) {
return $this->externalApiAdapter->makeApiCall($variable);
});
}
public function methodTwo ()
{
Cache::remember("key-2", (60 * 60) * 24, function () {
return $this->secondExternalApiAdapter->makeAnotherApiCall();
});
}已更新到此
public function methodOne ()
{
return Cache::remember("key-1", (60 * 60) * 24, function () use ($variable) {
return $this->externalApiAdapter->makeApiCall($variable);
});
}
public function methodTwo ()
{
return Cache::remember("key-2", (60 * 60) * 24, function () {
return $this->secondExternalApiAdapter->makeAnotherApiCall();
});
}在我的测试中,我只需Cache::flush();并继续使用我已经有的模拟类。
https://stackoverflow.com/questions/57390500
复制相似问题