logo

You don't need a closure to set up a mock

Skip the extra nesting

Joel Clermont
Joel Clermont
2026-11-19

If you've mocked a service in a Laravel test, you've probably written something like this:

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

$this->mock(PaymentGateway::class, function (MockInterface $mock) use ($order) {
    $mock->shouldReceive('charge')
        ->once()
        ->with($order->total)
        ->andReturnTrue();
});

It's the pattern the Laravel docs show, and it works fine. But there's some ceremony in there, which I think we should do without. You need to import MockInterface, nest your expectations one level deep, and remember to use any variables from the test.

The mock() method also returns the mock it creates, so you can skip the closure and chain your expectations right onto it:

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

$this->mock(PaymentGateway::class)
    ->shouldReceive('charge')
    ->once()
    ->with($order->total)
    ->andReturnTrue();

Same mock, same container binding, one less level of nesting.

If you need to set expectations on more than one method, capture the mock in a variable:

$gatewayMock = $this->mock(PaymentGateway::class);

$gatewayMock->shouldReceive('charge')->once()->andReturnTrue();
$gatewayMock->shouldNotReceive('refund');

Mockery will technically let you chain a second shouldReceive() onto the end of the first expectation. But then the start of each expectation gets buried in the middle of a long chain. Static analysis tools can also lose track of the types partway through a chain like that. With a variable, every expectation starts on its own line.

This isn't a big deal on its own. But tests get read far more often than they get written, and a test suite full of mocks adds up. I'd rather each one read top to bottom with as little noise as possible.

Here to help,

Joel

P.S. Our testing course spends three lessons on mocking, from setting up return values to tightening your mock assertions.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice.