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?

Brandon
  • 779
  • 5
  • 9
  • 28
rap-2-h
  • 30,204
  • 37
  • 167
  • 263

2 Answers2

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([]);
hidekuro
  • 413
  • 4
  • 13
  • What is Closure::class... when we use this. – saber tabatabaee yazdi Oct 07 '20 at 03:28
  • @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`. – s3c Nov 11 '22 at 13:43
-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

Ayo Akinyemi
  • 792
  • 4
  • 7