DEV Community

Cover image for Laravel Pest Mocking: Fakes, Mockery and Spies (Part 2)
devTalk
devTalk

Posted on Originally published at dev-talk.com

Laravel Pest Mocking: Fakes, Mockery and Spies (Part 2)

Last updated: 15 November 2026. Series: Part 2 of 3. Tested on Laravel 13.40, PHP 8.3.6, Pest 4.7.8, Mockery 1.6.15. Continues the orders app fromPart 1. Update log at the end.

The order endpoint sends an email, queues an invoice job, fires an event and calls a payment API. A test should check that each of those happened without sending a real email or charging a real card. Laravel gives you fakes for most of it, and Mockery for the rest. The hard part is knowing which to use and what each one can silently miss. Every example here was run, including the ways they fail.

Fake, mock or spy?

Tool Use it when Example
Laravel fake The thing is a Laravel service with a built-in fake Mail::fake(), Queue::fake(), Event::fake(), Http::fake()
Mock (Mockery) Your own class or interface; you want to assert how it is called and control what it returns mock(PaymentGateway::class, ...)
Spy You want to assert after the fact that something was, or was not, called spy(PaymentGateway::class)
Hand-written fake The behavior is simple and you want readable tests with no mocking library An anonymous class implementing the interface

In Pest, mock() and spy() come from the Laravel plugin as functions: use function Pest\Laravel\mock;. They bind the mock into the service container, so the controller receives it through its type-hint. That is why the payment gateway is behind an interface (Part 1): no code change is needed to swap it. Mockery itself is a separate package; the Pest documentation says to install it with composer require mockery/mockery --dev.

Laravel fakes

Mail and queue

use App\Jobs\GenerateInvoice;
use App\Mail\OrderConfirmation;
use App\Payments\PaymentGateway;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Mockery\MockInterface;

use function Pest\Laravel\mock;

beforeEach(function () {
    $this->user = User::factory()->create();
    $this->payload = ['sku' => 'book', 'quantity' => 2, 'payment_token' => 'tok_visa'];
});

it('sends the confirmation email', function () {
    Mail::fake();
    Queue::fake();
    mock(PaymentGateway::class, fn (MockInterface $m) => $m->shouldReceive('charge')->andReturn('ch_1'));

    $this->actingAs($this->user)->postJson('/orders', $this->payload)->assertCreated();

    Mail::assertSent(OrderConfirmation::class, function (OrderConfirmation $mail) {
        return $mail->hasTo($this->user->email) && $mail->order->quantity === 2;
    });
    Mail::assertSentCount(1);
});

it('queues the invoice job', function () {
    Queue::fake();
    Mail::fake();
    mock(PaymentGateway::class, fn (MockInterface $m) => $m->shouldReceive('charge')->andReturn('ch_1'));

    $this->actingAs($this->user)->postJson('/orders', $this->payload);

    Queue::assertPushed(GenerateInvoice::class, 1);
    Queue::assertPushed(GenerateInvoice::class, fn ($job) => $job->order->total_cents === 3000);
});
Enter fullscreen mode Exit fullscreen mode

The closure form of assertSent is the part that matters: it checks the recipient and the order, not just that "some mail went out". Fake before you act, assert after. A fake installed after the request has no effect on it.

A real bug the mail test caught

My first run of the mail test failed with The total number of mailables sent was 2 instead of 1. The listener was registered twice. Laravel discovers listeners in app/Listeners automatically (it matches the type-hint on the handle method), and I had also added Event::listen(OrderPlaced::class, SendOrderConfirmation::class) in the service provider. php artisan event:list showed it:

App\Events\OrderPlaced
  ⇂ App\Listeners\SendOrderConfirmation
  ⇂ App\Listeners\SendOrderConfirmation@handle
Enter fullscreen mode Exit fullscreen mode

In production that would have emailed every customer twice. The fix was deleting the manual Event::listen line; the list then showed one entry and the count was 1. This is why assertSentCount(1) is worth adding next to the closure assertion.

Events: fake only what you need

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

it('dispatches OrderPlaced', function () {
    Event::fake([OrderPlaced::class]);
    Queue::fake();
    mock(PaymentGateway::class, fn (MockInterface $m) => $m->shouldReceive('charge')->andReturn('ch_1'));

    $this->actingAs($this->user)->postJson('/orders', $this->payload);

    Event::assertDispatched(OrderPlaced::class);
});
Enter fullscreen mode Exit fullscreen mode

Pass the event classes you want faked. I also ran the version with a bare Event::fake() plus Mail::fake() and asserted the mail was sent. It failed with The expected [App\Mail\OrderConfirmation] mailable was not sent, because a bare Event::fake() fakes every event, so the listener never ran. I also confirmed that a bare Event::fake() stops Eloquent model events (a creating hook did not run), while Event::fake([OrderPlaced::class]) left them alone. Fake the specific event, or test the listener separately.

Failure paths

use App\Payments\PaymentFailed;

it('does not send mail when payment fails', function () {
    Mail::fake();
    Queue::fake();
    mock(PaymentGateway::class, fn (MockInterface $m) => $m->shouldReceive('charge')->andThrow(new PaymentFailed('nope')));

    $this->actingAs($this->user)->postJson('/orders', $this->payload)->assertUnprocessable();

    Mail::assertNothingSent();
    Queue::assertNothingPushed();
});
Enter fullscreen mode Exit fullscreen mode

"Nothing happens on failure" is where most side-effect bugs hide, and it is easy to forget. assertNothingSent() and assertNothingPushed() cover it.

Faking the HTTP client

If you keep the real gateway class and fake the network instead, use Http::fake(). Two features are worth knowing:

use Illuminate\Support\Facades\Http;

it('first call fails, second succeeds', function () {
    Http::preventStrayRequests();
    Http::fake([
        'payments.example.test/*' => Http::sequence()
            ->push(['error' => 'Card declined'], 402)
            ->push(['id' => 'ch_ok'], 201),
    ]);
    Queue::fake();
    Mail::fake();

    $this->actingAs($this->user)->postJson('/orders', $this->payload)->assertUnprocessable();
    $this->actingAs($this->user)->postJson('/orders', $this->payload)->assertCreated();

    Http::assertSentCount(2);
});

it('blocks a request nobody faked', function () {
    Http::preventStrayRequests();
    $this->withoutExceptionHandling();

    $this->actingAs($this->user)->postJson('/orders', $this->payload);
})->throws(RuntimeException::class);
Enter fullscreen mode Exit fullscreen mode

Http::sequence() returns the responses in order, which is how you test a retry or a flaky API. Http::preventStrayRequests() turns any request that does not match a fake into an exception, so a test can never reach a real server by accident. In the second test I disabled exception handling so the exception reaches the test instead of being turned into a 500 response. Put Http::preventStrayRequests() in a global beforeEach in tests/Pest.php if you want that protection everywhere.

Mocks: assert how your own class is called

it('charges the right amount', function () {
    Queue::fake();
    Mail::fake();
    mock(PaymentGateway::class, function (MockInterface $m) {
        $m->shouldReceive('charge')->once()->with(3000, 'tok_visa')->andReturn('ch_mock');
    });

    $this->actingAs($this->user)->postJson('/orders', $this->payload)->assertCreated();

    expect(Order::first()->payment_reference)->toBe('ch_mock');
});
Enter fullscreen mode Exit fullscreen mode

once() and with(3000, 'tok_visa') make this an assertion as well as a stub: the test fails if the controller charges a different amount, or twice, or not at all. The expectation is verified automatically when the test ends. To see what that failure looks like, I wrote an expectation that was never met:

Mockery\Exception\InvalidCountException: Method charge(<Any Arguments>) from
Mockery_2_App_Payments_PaymentGateway should be called exactly 1 times but called 0 times.
Enter fullscreen mode Exit fullscreen mode

The message is clear, but it points at Mockery, not at your code. Name your tests well so you know which expectation it was.

Spies: assert after the fact

use function Pest\Laravel\spy;

it('never charges when validation fails', function () {
    $gateway = spy(PaymentGateway::class);

    $this->actingAs($this->user)
        ->postJson('/orders', ['sku' => 'car'] + $this->payload)
        ->assertUnprocessable();

    $gateway->shouldNotHaveReceived('charge');
});

it('records the call', function () {
    Queue::fake();
    Mail::fake();
    $gateway = spy(PaymentGateway::class);
    $gateway->shouldReceive('charge')->andReturn('ch_spy');

    $this->actingAs($this->user)->postJson('/orders', $this->payload)->assertCreated();

    $gateway->shouldHaveReceived('charge')->once()->with(3000, 'tok_visa');
});
Enter fullscreen mode Exit fullscreen mode

The first test is the one a spy is best at: "this must not be called". With a plain mock you would write shouldReceive('charge')->never() up front; with a spy you keep the arrange step empty and check at the end. Note that in the second test I gave the spy a return value because the controller uses the result.

A hand-written fake

it('works with a hand-written fake', function () {
    Queue::fake();
    Mail::fake();
    $fake = new class implements PaymentGateway {
        public array $charges = [];

        public function charge(int $amountCents, string $token): string
        {
            $this->charges[] = [$amountCents, $token];

            return 'ch_fake';
        }
    };
    app()->instance(PaymentGateway::class, $fake);

    $this->actingAs($this->user)->postJson('/orders', $this->payload)->assertCreated();

    expect($fake->charges)->toBe([[3000, 'tok_visa']]);
});
Enter fullscreen mode Exit fullscreen mode

No Mockery, and the assertion reads as plain PHP. If you have many tests that need the same fake, move it to a class in tests/Support and reuse it. Fakes survive refactoring better than mocks, because they check the result, not the exact method calls.

Time

it('stamps the order with a frozen time', function () {
    $this->freezeSecond();
    Queue::fake();
    Mail::fake();
    mock(PaymentGateway::class, fn (MockInterface $m) => $m->shouldReceive('charge')->andReturn('ch_t'));

    $this->actingAs($this->user)->postJson('/orders', $this->payload);

    expect(Order::first()->created_at->equalTo(now()))->toBeTrue();
});
Enter fullscreen mode Exit fullscreen mode

My first version used $this->freezeTime() and failed: the frozen clock kept microseconds, but the database stored whole seconds, so equalTo returned false. freezeSecond() freezes at the start of the current second and matched. For tests that need a specific moment, use $this->travelTo(...).

What not to mock

  • Do not mock Eloquent models or the database. Feature tests with RefreshDatabase are fast enough, and a mocked query proves nothing about the real one.
  • Do not mock the class under test. If you have to, the class is probably doing too much.
  • Prefer fakes at the boundary (HTTP, mail, queue, storage) and assert on outcomes. A test that asserts every internal method call breaks on every refactor.
  • Fakes do not run the real thing. Mail::fake() never renders the email view; Queue::fake() never runs the job. Test the mailable's content and the job's handle() separately.

Common mistakes

  • Calling the fake after the request. Fake first.
  • A bare Event::fake() that also silences the listener you wanted to test.
  • Asserting "sent" without checking the recipient or count.
  • A shouldReceive with no return value when the code uses the result.
  • Letting a test reach the real API because Http::fake() did not match the URL. Use preventStrayRequests().
  • Comparing a frozen now() to a database timestamp without matching the precision.

Related Dev Talk articles

Frequently asked questions

What is the difference between a mock and a spy?

A mock declares what it expects before the code runs and fails if the expectation is not met. A spy records calls and you assert on them afterwards.

Do I need Mockery with Pest?

Only for mocks and spies. The Laravel fakes and hand-written fakes work without it. The Pest documentation recommends Mockery and shows how to install it.

Can I fake the payment gateway with Http::fake instead of a mock?

Yes, and it tests more of your real gateway class. A mock on the interface is faster and isolates the controller. Use both: mock in controller tests, Http::fake in a test of the gateway class.

update log

Update log

  • 15 November 2026: first published.
  • To recheck on each update: Pest Laravel plugin function names, and the fake and spy behavior in the current Laravel release.

Sources


Originally published on DEV Talk.

Top comments (0)