0
0
Laravelframework~5 mins

Mocking and faking in Laravel

Choose your learning style9 modes available
Introduction

Mocking and faking help you test your Laravel code by pretending parts of it work a certain way. This lets you check your code without using real services or data.

When you want to test a function that sends emails without actually sending them.
When you need to check how your app behaves if a database query returns specific data.
When you want to simulate a payment gateway response without real money transactions.
When testing code that calls external APIs to avoid slow or unreliable network calls.
When you want to isolate parts of your app to find bugs more easily.
Syntax
Laravel
use Illuminate\Support\Facades\Mail;

Mail::fake();

// Later in your test
Mail::assertSent(YourMailable::class);
Use ::fake() on Laravel facades to replace real behavior with fake versions.
Use assertions like assertSent to check if the fake was used as expected.
Examples
This example fakes the mail system, runs code that should send an email, then checks if the email was sent.
Laravel
use Illuminate\Support\Facades\Mail;

Mail::fake();

// Run code that sends email

Mail::assertSent(WelcomeEmail::class);
This fakes HTTP calls to a specific API and checks if the call was made.
Laravel
use Illuminate\Support\Facades\Http;

Http::fake([
    'api.example.com/*' => Http::response(['success' => true], 200),
]);

// Run code that calls the API

Http::assertSent(function ($request) {
    return $request->url() === 'https://api.example.com/data';
});
This example fakes the file storage disk and checks if a file was saved.
Laravel
use Illuminate\Support\Facades\Storage;

Storage::fake('local');

// Run code that stores files

Storage::disk('local')->assertExists('file.txt');
Sample Program

This test fakes the mail system, triggers a user registration event that should send a welcome email, then checks if the email was sent without actually sending it.

Laravel
<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;

class WelcomeEmailTest extends TestCase
{
    public function test_welcome_email_is_sent()
    {
        Mail::fake();

        // Simulate user registration that sends welcome email
        event(new \App\Events\UserRegistered());

        Mail::assertSent(WelcomeEmail::class);
    }
}
OutputSuccess
Important Notes

Always fake external services in tests to keep tests fast and reliable.

Use Laravel's built-in fakes for mail, HTTP, storage, and more.

Remember to assert that the fake was used to confirm your code works as expected.

Summary

Mocking and faking let you test code without real side effects.

Laravel provides easy ways to fake mail, HTTP, storage, and other services.

Use assertions to check that your code interacted with the fakes correctly.