We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
If you need to mock a Facade for testing in Laravel, it turns out to be really easy:
Unlike traditional static method calls, facades (including real-time facades) may be mocked. This provides a great advantage over traditional static > methods and grants you the same testability that you would have if you were using traditional dependency injection. When testing, you may often want to > mock a call to a Laravel facade that occurs in one of your controllers. For example, consider the following controller action:
namespace App\Http\Controllers; use Illuminate\Support\Facades\Cache; class UserController extends Controller { /** * Retrieve a list of all users of the application. */ public function index(): array { $value = Cache::get('key'); return [ // ... ]; } }
We can mock the call to the Cache facade by using the shouldReceive method, which will return an instance of a Mockery mock. Since facades are actually > resolved and managed by the Laravel service container, they have much more testability than a typical static class. For example, let's mock our call to > the Cache facade's get method:
use Illuminate\Support\Facades\Cache; test('get index', function () { Cache::shouldReceive('get') ->once() ->with('key') ->andReturn('value'); $response = $this->get('/users'); // ... });
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.