Topics Testing Mocks & Fakes
advanced 16 min read

Mocks & Fakes

Mocking services, faking facades, event faking, mail faking, queue faking, and notification faking.

Facades Faking

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;

// Fake events
Event::fake();
Event::assertDispatched(App\Events\PostCreated::class);

// Fake mail
Mail::fake();
Mail::assertSent(App\Mail\WelcomeMail::class);

// Fake notifications
Notification::fake();
Notification::assertSentTo($user, App\Notifications\InvoicePaid::class);

// Fake queue
Queue::fake();
Queue::assertPushed(App\Jobs\ProcessPodcast::class);

HTTP Faking

use Illuminate\Support\Facades\Http;

Http::fake([
"github.com/*" => Http::response(["login" => "octocat"], 200),
]);

Http::assertSent(function (Request $request) {
return $request->url() === "https://api.github.com/user";
});

Storage Faking

Storage::fake("s3");
$file = UploadedFile::fake()->image("photo.jpg");
$this->post("/photos", ["photo" => $file]);
Storage::disk("s3")->assertExists("photos/photo.jpg");

Examples

<?php
namespace Tests\Feature;

use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class ExternalApiTest extends TestCase
{
    public function test_github_api_call(): void
    {
        Http::fake([
            'api.github.com/*' => Http::response(['login' => 'laravel'], 200),
        ]);

        \$response = \$this->get('/github-user');
        \$response->assertSee('laravel');
        Http::assertSent(fn(\$r) => str_contains(\$r->url(), 'api.github.com'));
    }
}

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.