如何在 phpunit 测试中使用带有模拟缓存的缓存标签?

Jon*_*nas 3 phpunit caching mocking laravel

我已经在 Laravel 项目上实现了缓存标签,并且我的控制器中有类似的内容:

if (Cache::tags(['api'])->has('someKey')) {
    return new JsonResponse(Cache::tags(['api'])->get('someKey'));
}
Run Code Online (Sandbox Code Playgroud)

我想编写一个 phpunit 测试来测试这段代码:我模拟了 Laravel 文档中的缓存,但我还没有找到任何关于如何tags在模拟缓存上使用的内容

我试过 :

Cache::tags(['api'])->shouldReceive('has')->with('someKey')->andReturn(true)->once();
Run Code Online (Sandbox Code Playgroud)

或者

Cache::shouldReceive('has')->tags(['api'])->with('someKey')->andReturn(true)->once();
Run Code Online (Sandbox Code Playgroud)

但这都不起作用,我得到了Call to undefined method Illuminate\Cache\ArrayStore::shouldReceive()call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'tags'

有人知道吗?多谢 :)

mrh*_*rhn 5

您将需要模拟标签本身调用并使用它->andReturnSelf()才能创建模拟链。因此调用Cache::tags(['api'])返回模拟实例。

Cache::shouldReceive('tags')->with(['api'])->andReturnSelf();

Cache::shouldReceive('has')->once()->with('someKey')->andReturn(true);
Cache::shouldReceive('get')->once()->with('someKey')->andReturn('result');
Run Code Online (Sandbox Code Playgroud)