How to mock Cache::remember in Laravel
Asked Answered
T

2

7

Within a unit test method, I tried to mock a Cache::remember response like this:

Cache::shouldReceive('remember')
    ->once()
    ->with('my_key', 120, function() {}) // There are 3 args in remember method
    ->andReturn([]);

But I get this error:

exception 'Mockery\Exception\NoMatchingExpectationException' with message 'No matching handler found for Mockery_0_Illuminate_Cache_CacheManager::remember ("my_key", 120, object(Closure)). Either the method was unexpected or its arguments matched no expected argument list for this method

I don't understand why I got this error and did not found anything in Laravel documentation about this. It says there is no matching, but it seems to match.

How can I mock a Cache::remember response?

Thoroughwort answered 30/12, 2015 at 10:10 Comment(0)
D
13

replace 3rd argument of with method to \Closure::class to matching any closures.

Cache::shouldReceive('remember')
    ->once()
    ->with('my_key', 120, \Closure::class)
    ->andReturn([]);
Disinterest answered 1/5, 2018 at 3:38 Comment(2)
What is Closure::class... when we use this.Stitch
@sabertabatabaeeyazdi Closure is basically a type of any function, regardless of it's parameters or return values, that has no name ie. an anonymous function (function (...) {...}), or an anonymous arrow function (fn (...) => ...), but not a named function/method (function iHaveAName(...) {...}). The way OP put in the third argument, the shouldReceive method expects this exact function (not just the same), so you use Closure::class instead, to indicate the third argument must be some anonymous function, which includes whatever function is actually passed to shouldReceive.Mawson
C
-1

See this issue about challenges with mocking the Cache facade -

https://github.com/laravel/framework/issues/10803

also reference

https://github.com/laravel/framework/issues/9729

Cirilla answered 30/12, 2015 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.