dtqjbbr5283 2019-08-07 08:52
浏览 94

Laravel模拟2个单独的Cache ::记得在同一个测试中

I am writing a test for a console command. In the command we make 2 separate api calls to external services which I can mock fine. But both of those external calls are wrapped in Cache::remember. I want to able to mock both of those Caches in my test, but can't seem to figure it out. I can only seem to mock the first one. They have different keys.

So for example, my console command has something like this (which I have simplified for the 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();
});

In my test, I want one of the Caches to return null, and the other to return a mocked object.

Here is the first one.

Cache::shouldReceive('remember')
    ->with('key-1', (60 * 60) * 24, \Closure::class)
    ->andReturn(null);

If I out put the second one in

$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));

it sill returns null.

How can I mock the second Cache please.

  • 写回答

2条回答 默认 最新

  • drbl91357 2019-08-07 09:27
    关注

    You can use ->once() for such purposes.

    // 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));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多