How can I use cache tags whith a mocked Cache in phpunit tests?

Viewed 607

I have implemented Cache tags on a laravel project and I have something like this in my controller :

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

I would like to write a phpunit test to test this code : I mocked the Cache like found in the laravel documentation, but I haven't found anything on how to use tags on a mocked cache

I tried :

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

or

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

But none of this works, I got Call to undefined method Illuminate\Cache\ArrayStore::shouldReceive() or call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'tags'

Does anybody have a clue ? thanks a lot :)

1 Answers

You will need to mock tags call by itself and use ->andReturnSelf() to be able to make the mock chain. So calling Cache::tags(['api']) returns the mock instance.

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

Cache::shouldReceive('has')->once()->with('someKey')->andReturn(true);
Cache::shouldReceive('get')->once()->with('someKey')->andReturn('result');
Related