Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 67 ยท Testing

Faking Mail, Queues, Events, HTTP and Time

Learn Laravel's fakes - Mail, Queue, Event, Http and Storage fakes, freezeTime and Mockery - and how the fake-facade pattern works with a runnable example.

Real applications send emails, push jobs to queues, call other people's APIs and depend on the clock. None of that belongs in a test. You do not want your test suite to email customers, wait for a slow API, or fail only on Mondays. The solution is a test double: a stand-in that replaces the real thing and records what your code tried to do.

Laravel builds this into its facades. Calling Mail::fake() swaps the real mailer for a recording fake, and a family of assertSent-style methods lets you check what happened. This lesson shows the fakes you will use most, freezeTime(), and Mockery for everything else. The Laravel code is read-only; the runnable examples show how the fake-facade pattern works in plain PHP.

The idea: fake, act, assert

Every fake test has three steps:

  1. Fake the service so nothing real happens.
  2. Act by running the code under test, usually through an HTTP request.
  3. Assert that the fake recorded the right interaction.
flowchart LR
    A["Test calls Mail::fake()"] --> B["Container now holds a fake mailer"]
    B --> C["Controller calls Mail::to()->send()"]
    C --> D["Fake records the mailable"]
    D --> E["Test asserts: Mail::assertSent()"]

Facades look up their service in the container, so replacing the container entry replaces the behavior everywhere.

Mail::fake()

PHP
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;

test('shipping an order emails the customer', function () {
    Mail::fake();

    $order = Order::factory()->create();

    $this->actingAs(User::factory()->admin()->create())
        ->post("/orders/{$order->id}/ship")
        ->assertRedirect();

    Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
        return $mail->hasTo($order->customer->email);
    });
    Mail::assertSentCount(1);
});

test('a draft order sends nothing', function () {
    Mail::fake();

    // ... act ...

    Mail::assertNothingSent();
});

The closure receives each sent mailable and returns true for the one you expect. Use assertQueued() instead of assertSent() when your mailable implements ShouldQueue. See Sending Mail.

Queue::fake() and Bus::fake()

With the queue faked, dispatched jobs are recorded and never run:

PHP
use App\Jobs\ProcessPodcast;
use Illuminate\Support\Facades\Queue;

test('uploading a podcast queues processing', function () {
    Queue::fake();

    $this->post('/podcasts', [...]);

    Queue::assertPushed(ProcessPodcast::class);
    Queue::assertPushedOn('media', ProcessPodcast::class);
    Queue::assertNotPushed(SendNewsletter::class);
});

Because the job does not run, you test two things separately: that the right job was dispatched (above), and that the job's handle() method does the right thing when called directly. For chains and batches use Bus::fake() with assertChained() and assertBatched(). See Queues and Jobs.

Event::fake()

PHP
use App\Events\OrderPlaced;
use Illuminate\Support\Facades\Event;

test('placing an order fires an event', function () {
    Event::fake();

    $this->post('/orders', [...]);

    Event::assertDispatched(OrderPlaced::class);
    Event::assertNotDispatched(OrderCancelled::class);
});

A plain Event::fake() stops all listeners from running. To fake only some events and let the rest behave normally, pass them in: Event::fake([OrderPlaced::class]). Be careful: Eloquent model events also go through the dispatcher, so faking everything can silence observers your test needs. See Events and Listeners.

Http::fake()

Outgoing HTTP calls made with the Laravel HTTP client can be given canned answers by URL pattern:

PHP
use Illuminate\Support\Facades\Http;

test('it shows the exchange rate', function () {
    Http::fake([
        'api.rates.test/*' => Http::response(['eur' => 0.92], 200),
        '*'                => Http::response('unexpected', 500),
    ]);

    $this->get('/prices')->assertSee('0.92');

    Http::assertSent(fn ($request) => $request->url() === 'https://api.rates.test/latest');
});

Add Http::preventStrayRequests() in your base test setup. Then any request that matches no fake throws an exception instead of silently reaching the internet, which catches forgotten fakes immediately.

Storage::fake() and Notification::fake()

Storage::fake('public') swaps a disk for a temporary directory that is wiped between tests, so upload tests never touch real files:

PHP
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

test('an avatar can be uploaded', function () {
    Storage::fake('public');

    $this->actingAs(User::factory()->create())
        ->post('/avatar', ['avatar' => UploadedFile::fake()->image('me.jpg')])
        ->assertRedirect();

    Storage::disk('public')->assertExists('avatars/me.jpg');
});

Notification::fake() works like Mail::fake() with Notification::assertSentTo($user, WelcomeNotification::class). See Notifications.

Freezing time

Code that reads the clock gives different answers every second. Carbon, Laravel's date library, lets a test pin "now":

PHP
test('a trial expires after 14 days', function () {
    $this->freezeTime();                       // now stops moving
    $user = User::factory()->create(['trial_ends_at' => now()->addDays(14)]);

    $this->travel(15)->days();                 // jump forward
    expect($user->trialExpired())->toBeTrue();

    $this->travelBack();
});

freezeTime() stops the clock at the current moment, travelTo(Carbon::parse('2030-01-01')) jumps to an exact date, and travel(5)->hours() moves relative to now. After the test, Laravel restores real time. This is the same idea as injecting a clock, covered in Testing PHP Code.

Mockery for everything else

When there is no built-in fake, Laravel ships Mockery and a helper that binds a mock into the container:

PHP
use App\Services\PaymentGateway;

test('a declined card shows an error', function () {
    $this->mock(PaymentGateway::class, function ($mock) {
        $mock->shouldReceive('charge')
            ->once()
            ->with(1999, 'tok_visa')
            ->andReturn(false);
    });

    $this->post('/checkout', ['token' => 'tok_visa'])
        ->assertSessionHasErrors('card');
});

mock() replaces the binding fully; partialMock() keeps real behavior for methods you do not define; spy() records calls so you can assert afterwards with shouldHaveReceived(). Mock only what you own or what crosses a boundary (payment gateways, third-party clients). Mocking Eloquent models or your own simple classes makes tests brittle: use factories and a test database instead.

How a fake-facade works

Here is the pattern in plain PHP: a facade that forwards static calls to whatever sits in a registry. Mail::fake() replaces the real service with a recorder, and the same assertSent() call can then inspect it. This is a simplified stand-in, not Laravel's code.

PHP A fake facade and recorder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The function shipOrder() never changes. It calls Mail::send(), and the test decides whether that reaches a real server or a recorder. Laravel does this with the service container: a facade asks the container for its underlying object, and fake() swaps that object.

Faking a time source and an HTTP client

The same idea works without facades whenever you inject a dependency. A closure or small interface for "now" and for "fetch a URL" makes both trivially fakeable:

PHP Fake clock and fake HTTP responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last lines mimic Http::preventStrayRequests(): a request that matches no fake raises an error, so a test can never accidentally depend on the network.

Fake at the boundary, assert on the outcome. A test that says "the customer received a shipped email" survives refactoring; a test that checks which internal methods were called breaks every time you reorganize.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Queue::fake() do to a dispatched job?

    With the queue faked, jobs are recorded so you can call Queue::assertPushed(), but their handle() methods never run.
  2. 2. Which helper stops the clock so now() returns the same moment during a test?

    freezeTime() pins Carbon's notion of now. travelTo() and travel() move it to other moments, and Laravel resets it afterwards.
  3. 3. Why call Http::preventStrayRequests() in tests?

    Without it, a forgotten fake silently sends a real request. With it, the test fails and tells you which URL was unexpected.
  4. 4. When is Mockery the right tool?

    Mock services that cross a boundary (gateways, third-party clients). Prefer factories and a test database for your own models.
  5. 5. A test fakes Mail and then asserts Mail::assertQueued(). When is that the right assertion?

    A queued mailable is pushed to the queue instead of being sent immediately, so assertQueued() checks it. assertSent() is for mail sent synchronously.

Summary

  • Fake, act, assert: replace the real service, run your code, check what the fake recorded.
  • Mail::fake(), Queue::fake(), Event::fake(), Http::fake(), Storage::fake() and Notification::fake() each come with matching assert... methods.
  • Http::preventStrayRequests() stops tests from reaching the real internet.
  • freezeTime(), travelTo() and travel() control the clock.
  • Use Mockery through $this->mock() only for boundaries you do not own.
  • The runnable examples are plain-PHP stand-ins that show the pattern, not Laravel's implementation.

Next: Browser Tests, Static Analysis and Code Style