【问题标题】:How can I use cache tags whith a mocked Cache in phpunit tests?如何在 phpunit 测试中使用带有模拟缓存的缓存标签?
【发布时间】:2020-09-18 21:17:01
【问题描述】:

我在 laravel 项目中实现了缓存标签,我的控制器中有这样的东西:

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

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

我试过了:

Cache::tags(['api'])->shouldReceive('has')->with('someKey')->andReturn(true)->once();

Cache::shouldReceive('has')->tags(['api'])->with('someKey')->andReturn(true)->once();

但这些都不起作用,我得到了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'

有人知道吗?非常感谢:)

【问题讨论】:

    标签: laravel caching mocking phpunit


    【解决方案1】:

    您需要自己模拟标签调用并使用->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');
    

    【讨论】:

    • 在修补程序中运行它,它应该可以工作,否则写评论,我很乐意提供帮助:)
    猜你喜欢
    • 2011-02-08
    • 2019-02-20
    • 2011-01-29
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    相关资源
    最近更新 更多