Skip to content

Lesson 40 of 45 · Testing as a Discipline

Test Doubles - Mocks, Stubs, Fakes and Spies

Intermediate•
lesson•
November 7, 2026•
~16 min read

"We mocked it"

The word "mock" gets used as a verb for everything. "We mocked the database." "We mocked the mailer." "We mocked the cache." If you ask five PHP developers what they meant, you'll get five different things back. Some really did write a mock with assertions. Some replaced an interface with a fake implementation. Some passed a class that returns canned values. All of them call it "mocking".

The vocabulary matters. Each kind of test double does a different job, and using the wrong one in the wrong place makes a test suite brittle and hard to refactor.

This lesson sorts them out. The taxonomy comes from Gerard Meszaros's xUnit Test Patterns and Martin Fowler's "Mocks Aren't Stubs", and the five kinds have specific meanings worth knowing.

The five kinds

Meszaros names five categories. In conversation they usually get collapsed into two or three, but the full set is worth knowing.

Dummy. A placeholder. Passes type checks but is never actually used. Common for satisfying constructor signatures when the test doesn't exercise that collaborator.

Stub. Provides canned answers to specific queries. Doesn't track interactions; just returns what was set up. The simplest "I need this method to return X" double.

Fake. A working implementation with shortcuts. An in-memory repository, a fake mailer that puts messages in an array, a fake clock that returns a fixed time. Real behavior, simplified for the test environment.

Spy. Records the interactions it had. Like a stub, but you can ask it after the test, "did anyone call you with X?". Good for verifying side effects without forcing a strict interaction script.

Mock. Pre-programmed with expectations: "you will be called twice, with these arguments, in this order". The test fails if the expectations aren't met. The strictest kind.

The usual collapse:

  • Dummies and stubs together (any "returns canned data" double is "a stub").

  • Spies and mocks together (any "records or asserts on calls" is "a mock").

That collapse is fine in conversation. In code reviews and design discussions, the five-way split clarifies what kind of double a specific test is using and why.

Examples in PHP

Dummy. GuestNameFormatter takes a logger it only uses when a name is empty:

PHP
<?php declare(strict_types=1); namespace App\Booking; use Psr\Log\LoggerInterface; final readonly class GuestNameFormatter { public function __construct(private LoggerInterface $logger) {} public function format(string $firstName, string $lastName): string { if (trim($firstName) === '' || trim($lastName) === '') { $this->logger->warning('Formatting an incomplete guest name'); } return trim($firstName . ' ' . $lastName); } }
PHP
<?php declare(strict_types=1); namespace Tests\Booking; use App\Booking\GuestNameFormatter; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; final class GuestNameFormatterTest extends TestCase { public function test_it_joins_first_and_last_name(): void { $dummyLogger = new NullLogger(); // never asserted on $formatter = new GuestNameFormatter($dummyLogger); $this->assertSame('Ada Lovelace', $formatter->format('Ada', 'Lovelace')); } }

The null logger from the Null Object lesson is the canonical dummy: it satisfies the contract and does nothing. This test never reaches the warning branch, so the constructor needs a logger and the test supplies one. That is the line between the two kinds of double: a null object passed only to satisfy a constructor is a dummy, and an in-memory repository is a fake.

Stub. TotalCalculator sums prices in one currency and asks an ExchangeRates collaborator to convert each one. ExchangeRates is an interface with one method:

PHP
<?php declare(strict_types=1); namespace App\Billing; interface ExchangeRates { public function convert(Money $amount, Currency $to): Money; }

TotalCalculator takes it through its constructor:

PHP
<?php declare(strict_types=1); namespace App\Billing; final readonly class TotalCalculator { public function __construct(private ExchangeRates $exchangeRates) {} /** @param list<Money> $prices */ public function totalIn(array $prices, Currency $currency): Money { $total = Money::zero($currency); foreach ($prices as $price) { $total = $total->add($this->exchangeRates->convert($price, $currency)); } return $total; } }
PHP
<?php declare(strict_types=1); namespace Tests\Billing; use App\Billing\Currency; use App\Billing\ExchangeRates; use App\Billing\Money; use App\Billing\TotalCalculator; use PHPUnit\Framework\TestCase; final class TotalCalculatorTest extends TestCase { public function test_it_totals_prices_converted_by_the_stub(): void { $stubExchangeRates = $this->createStub(ExchangeRates::class); $stubExchangeRates->method('convert') ->willReturn(Money::fromCents(11000, Currency::eur())); // canned answer $calculator = new TotalCalculator($stubExchangeRates); $total = $calculator->totalIn([Money::fromCents(10000, Currency::usd())], Currency::eur()); $this->assertSame(11000, $total->amountInCents); } }

The stub returns whatever the test needs, whoever asks, and doesn't track calls. createStub() is PHPUnit's built-in way to make one, and it's the simplest "make this method return X" double.

Fake. The fake implements the whole Guests interface, which has three methods. Guests and GuestNotFound are the interface and exception from the domain exceptions lesson:

PHP
<?php declare(strict_types=1); namespace App\Testing; use App\Booking\EmailAddress; use App\Booking\Exceptions\DuplicateGuestEmail; use App\Booking\Exceptions\GuestNotFound; use App\Booking\Guest; use App\Booking\GuestId; use App\Booking\Guests; final class InMemoryGuests implements Guests { /** @var array<string, Guest> */ private array $rows = []; public function withId(GuestId $id): Guest { return $this->rows[$id->value] ?? throw new GuestNotFound($id); } public function withEmail(EmailAddress $email): ?Guest { foreach ($this->rows as $guest) { if ($guest->email->value === $email->value) { return $guest; } } return null; } public function save(Guest $guest): void { foreach ($this->rows as $existing) { if ($existing->id->value !== $guest->id->value && $existing->email->value === $guest->email->value) { throw new DuplicateGuestEmail($guest->email); } } $this->rows[$guest->id->value] = $guest; } }

The fake is a real repository implementation, just backed by an array instead of the database. Like the unique index behind EloquentGuests::save(), it refuses a second guest with the same email by throwing DuplicateGuestEmail. The test can save guests, retrieve them, and verify behavior end-to-end on the repository's interface, without any database setup.

In my experience this is the most underused kind of double in PHP, and the one that pays back the most. A fake repository is faster than a real database, more honest than a stub, and lets the test exercise actual repository behavior.

Two more fakes are used elsewhere in the course, so they are shown in full here. InMemoryReservations implements the Reservations repository:

PHP
<?php declare(strict_types=1); namespace App\Testing; use App\Booking\RoomId; use App\Reservations\DateRange; use App\Reservations\Exceptions\ReservationNotFound; use App\Reservations\Reservation; use App\Reservations\ReservationCollection; use App\Reservations\ReservationId; use App\Reservations\Reservations; use App\Reservations\ReservationStatus; use DateTimeImmutable; final class InMemoryReservations implements Reservations { /** @var array<string, Reservation> */ private array $rows = []; public function withId(ReservationId $id): Reservation { return $this->rows[$id->value] ?? throw new ReservationNotFound($id); } public function existingFor(RoomId $roomId, DateRange $stayDates): ReservationCollection { return new ReservationCollection(...array_values(array_filter( $this->rows, fn (Reservation $reservation): bool => $reservation->roomId->value === $roomId->value && $reservation->stayDates->overlaps($stayDates), ))); } public function save(Reservation $reservation): void { $this->rows[$reservation->id->value] = $reservation; } public function pendingCheckInsOn(DateTimeImmutable $date): ReservationCollection { return new ReservationCollection(...array_values(array_filter( $this->rows, fn (Reservation $reservation): bool => $reservation->status() === ReservationStatus::Confirmed && $reservation->stayDates->checkIn->format('Y-m-d') === $date->format('Y-m-d'), ))); } }

pendingCheckInsOn filters the way EloquentReservations does in the Repository lesson: Confirmed status and check-in date. It reads the status through Reservation::status().

FakePayments implements the Payments port. It succeeds every time and remembers what it was asked to do:

PHP
<?php declare(strict_types=1); namespace App\Testing; use App\Billing\Money; use App\Payments\PaymentAuthorization; use App\Payments\PaymentCapture; use App\Payments\PaymentId; use App\Payments\PaymentRefund; use App\Payments\Payments; use App\Reservations\ReservationId; final class FakePayments implements Payments { /** @var list<PaymentRefund> */ public array $refunds = []; public function authorize(ReservationId $id, Money $amount): PaymentAuthorization { return new PaymentAuthorization(PaymentId::next()); } public function capture(PaymentId $id): PaymentCapture { return new PaymentCapture($id); } public function refund(PaymentId $id, Money $amount): PaymentRefund { return $this->refunds[] = new PaymentRefund($id, $amount); } }

A test reads $payments->refunds afterward to check what was given back, so this fake is also a spy.

Spy. The course has its own small EventDispatcher interface (with a Laravel-backed implementation for production). RecordingDispatcher, shown in Lesson 13 of this course, is a spy for it: it implements the interface in full and appends every event it receives to a public $dispatched list.

The tests in the rest of this lesson use the RegisterGuestCommandHandler from the Result pattern lesson. FrozenClock is the test clock from the dependency injection lesson; in Symfony, Symfony\Component\Clock\MockClock does the same job and takes the moment in its constructor. In the test:

PHP
<?php declare(strict_types=1); namespace Tests\Booking; use App\Booking\Events\GuestRegistered; use App\Booking\RegisterGuestCommand; use App\Booking\RegisterGuestCommandHandler; use App\Testing\FrozenClock; use App\Testing\InMemoryGuests; use App\Testing\RecordingDispatcher; use Illuminate\Hashing\BcryptHasher; use PHPUnit\Framework\TestCase; final class RegisterGuestCommandHandlerTest extends TestCase { public function test_it_dispatches_guest_registered(): void { $dispatcher = new RecordingDispatcher(); $handler = new RegisterGuestCommandHandler( guests: new InMemoryGuests(), hasher: new BcryptHasher(['rounds' => 4]), clock: new FrozenClock('2026-06-01 12:00:00'), events: $dispatcher, ); $command = new RegisterGuestCommand( email: 'ada@example.com', name: 'Ada Lovelace', password: 'a-long-passphrase-123', ); $handler->handle($command); $this->assertCount(1, $dispatcher->dispatched); $this->assertInstanceOf(GuestRegistered::class, $dispatcher->dispatched[0]); } }

The spy records what happened and the test asserts on the recording afterward, so the handler doesn't know it's being watched and the test doesn't predeclare which calls to expect.

Mock. ConfirmationNotifier hands a mailable to Laravel's mailer:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Reservations\Mail\ReservationConfirmedEmail; use Illuminate\Contracts\Mail\Mailer; final readonly class ConfirmationNotifier { public function __construct(private Mailer $mailer) {} public function notify(ReservationConfirmedEmail $email): void { $this->mailer->send($email); } }
PHP
<?php declare(strict_types=1); namespace Tests\Reservations; use App\Reservations\ConfirmationNotifier; use App\Reservations\Mail\ReservationConfirmedEmail; use App\Reservations\ReservationId; use Illuminate\Contracts\Mail\Mailer; use PHPUnit\Framework\TestCase; final class ConfirmationNotifierTest extends TestCase { public function test_it_sends_the_confirmation_email(): void { $email = new ReservationConfirmedEmail(ReservationId::next()); $mock = $this->createMock(Mailer::class); $mock ->expects($this->once()) ->method('send') ->with($email); $notifier = new ConfirmationNotifier($mock); $notifier->notify($email); } }

The mock is set up before the test runs with strict expectations. If the mailer isn't called exactly once with that email, the test fails. PHPUnit's createMock and Mockery's mock objects are the canonical PHP versions. In a Symfony app the constructor takes Symfony\Component\Mailer\MailerInterface instead, and the mock expects its send() method.

Mocks are the strictest. They couple the test to which methods get called, not just to outcomes. A refactor that achieves the same effect through different calls breaks the test.

When to use which

A few practical rules:

  • For dependencies you don't care about in this test: dummy. The null implementation is the cleanest.

  • For "this method should return X for this test": stub. Don't reach for a mock just because you need a canned answer.

  • For collaborators you'd otherwise need a real database/queue/cache for: fake. Build a small in-memory implementation that satisfies the contract. Reuse it across tests.

  • For verifying side effects (events dispatched, jobs queued, emails recorded): spy. Recording doubles let you assert on outcomes without prescribing call counts.

  • For verifying interaction protocols where the call sequence is part of the contract: mock. A webhook signed in a specific way and a state machine that fires in a specific order are examples. This is rare in my experience. Most "I need to verify this got called" can be done with a spy or by checking the resulting state.

The strongest single piece of advice is to prefer fakes and spies over mocks, because a suite full of mocks fights every refactor.

Why fakes often beat mocks

Consider testing a handler that registers a guest. The mock-heavy version:

PHP
<?php declare(strict_types=1); namespace Tests\Booking; use App\Booking\EmailAddress; use App\Booking\Events\GuestRegistered; use App\Booking\Guest; use App\Booking\Guests; use App\Booking\RegisterGuestCommand; use App\Booking\RegisterGuestCommandHandler; use App\Framework\Events\EventDispatcher; use App\Testing\FrozenClock; use Illuminate\Contracts\Hashing\Hasher; use PHPUnit\Framework\TestCase; final class RegisterGuestHandlerMockHeavyTest extends TestCase { public function test_register_guest_with_mocks(): void { $guests = $this->createMock(Guests::class); $guests->expects($this->once()) ->method('withEmail') ->with($this->equalTo(new EmailAddress('ada@example.com'))) ->willReturn(null); $guests->expects($this->once()) ->method('save') ->with($this->isInstanceOf(Guest::class)); $events = $this->createMock(EventDispatcher::class); $events->expects($this->once()) ->method('dispatch') ->with($this->isInstanceOf(GuestRegistered::class)); $hasher = $this->createStub(Hasher::class); $hasher->method('make')->willReturn('hashed-password'); $handler = new RegisterGuestCommandHandler( guests: $guests, hasher: $hasher, clock: new FrozenClock('2026-06-01 12:00:00'), events: $events, ); $handler->handle(new RegisterGuestCommand( email: 'ada@example.com', name: 'Ada Lovelace', password: 'a-long-passphrase-123', )); } }

The fake-heavy version:

PHP
<?php declare(strict_types=1); namespace Tests\Booking; use App\Booking\EmailAddress; use App\Booking\Events\GuestRegistered; use App\Booking\Guest; use App\Booking\RegisterGuestCommand; use App\Booking\RegisterGuestCommandHandler; use App\Testing\FrozenClock; use App\Testing\InMemoryGuests; use App\Testing\RecordingDispatcher; use Illuminate\Hashing\BcryptHasher; use PHPUnit\Framework\TestCase; final class RegisterGuestHandlerFakeHeavyTest extends TestCase { public function test_register_guest_with_fakes(): void { $guests = new InMemoryGuests(); $dispatcher = new RecordingDispatcher(); $handler = new RegisterGuestCommandHandler( guests: $guests, hasher: new BcryptHasher(['rounds' => 4]), clock: new FrozenClock('2026-06-01 12:00:00'), events: $dispatcher, ); $handler->handle(new RegisterGuestCommand( email: 'ada@example.com', name: 'Ada Lovelace', password: 'a-long-passphrase-123', )); $saved = $guests->withEmail(new EmailAddress('ada@example.com')); $this->assertInstanceOf(Guest::class, $saved); $this->assertCount(1, $dispatcher->dispatched); $this->assertInstanceOf(GuestRegistered::class, $dispatcher->dispatched[0]); } }

Refactor the handler to call withEmail twice, and the mock version fails even though the behavior is identical. The fake version only checks that a guest exists and an event was dispatched, so it survives the same refactor.

Contract tests: keeping the fake honest

A fake is only useful if it behaves the same way as the real implementation behind the same interface. If InMemoryReservations allows something the database-backed repository rejects, or fails to throw where the database-backed one would, a test that passes against the fake proves nothing about production.

A contract test closes that gap. It's a single abstract PHPUnit test case written once against the interface, with one abstract method that supplies the repository to test. The base class extends the application's Laravel Tests\TestCase, because the Eloquent subclass needs a booted container:

PHP
<?php declare(strict_types=1); namespace Tests\Reservations; use App\Booking\RoomId; use App\Reservations\DateRange; use App\Reservations\Exceptions\ReservationNotFound; use App\Reservations\ReservationId; use App\Reservations\Reservations; use App\Reservations\ReservationStatus; use App\Testing\ReservationBuilder; use Carbon\CarbonImmutable; use DateTimeImmutable; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; abstract class ReservationsContract extends TestCase { abstract protected function createRepository(): Reservations; #[Test] public function it_returns_a_saved_reservation_by_id(): void { $repository = $this->createRepository(); $reservation = ReservationBuilder::new()->build(); $repository->save($reservation); $found = $repository->withId($reservation->id); $this->assertSame($reservation->id->value, $found->id->value); } #[Test] public function it_throws_when_the_id_does_not_exist(): void { $repository = $this->createRepository(); $this->expectException(ReservationNotFound::class); $repository->withId(new ReservationId('missing')); } #[Test] public function it_finds_reservations_that_overlap_a_stay_in_the_same_room(): void { $repository = $this->createRepository(); $repository->save(ReservationBuilder::new()->build()); $repository->save(ReservationBuilder::new()->forRoom(new RoomId(202))->build()); $overlapping = DateRange::ofNights(CarbonImmutable::parse('2026-06-02'), 2); $this->assertCount(1, $repository->existingFor(new RoomId(101), $overlapping)); } #[Test] public function it_does_not_count_a_stay_that_starts_on_the_check_out_day(): void { $repository = $this->createRepository(); $repository->save(ReservationBuilder::new()->build()); $adjacent = DateRange::ofNights(CarbonImmutable::parse('2026-06-03'), 2); $this->assertCount(0, $repository->existingFor(new RoomId(101), $adjacent)); } #[Test] public function it_lists_only_confirmed_reservations_as_pending_check_ins(): void { $repository = $this->createRepository(); $confirmed = ReservationBuilder::new()->withStatus(ReservationStatus::Confirmed); $repository->save($confirmed->build()); $repository->save(ReservationBuilder::new()->build()); $repository->save($confirmed->checkingInOn(new DateTimeImmutable('2026-06-02'))->build()); $pending = $repository->pendingCheckInsOn(new DateTimeImmutable('2026-06-01')); $this->assertCount(1, $pending); } }

The two stay tests pin down the overlap rule (a stay that begins on the check-out day does not collide) and the last one pins down the status filter, the two places a hand-written fake is most likely to drift from the SQL.

Each real implementation gets a thin subclass that provides its own repository, InMemoryReservations for speed, EloquentReservations for a check against the database:

PHP
<?php declare(strict_types=1); namespace Tests\Reservations; use App\Reservations\Reservations; use App\Testing\InMemoryReservations; final class InMemoryReservationsContractTest extends ReservationsContract { protected function createRepository(): Reservations { return new InMemoryReservations(); } }
PHP
<?php declare(strict_types=1); namespace Tests\Reservations; use App\Reservations\Infrastructure\EloquentReservations; use App\Reservations\Reservations; use Illuminate\Foundation\Testing\RefreshDatabase; final class EloquentReservationsContractTest extends ReservationsContract { use RefreshDatabase; protected function createRepository(): Reservations { return new EloquentReservations(); } }

The Eloquent subclass needs ReservationModel and the reservations table, both shown in Lesson 39 of this course.

Both subclasses run the identical assertions from the parent. If InMemoryReservations ever drifts from what EloquentReservations actually does, one of these two catches it on the next test run, before production does.

PHPUnit, Mockery, and the ecosystem

A few practical PHP notes:

PHPUnit's createStub() and createMock(). Built into PHPUnit. Use createStub() when the test needs canned answers and doesn't check calls. Use createMock() only when you set expectations with expects(): the PHPUnit 12.5 docs say that creating a mock without configuring any expectations makes PHPUnit emit a notice, and suggest createStub() instead. Neither expresses stateful behavior easily, which is where fakes come in.

Mockery. A third-party mocking library with its own expectation syntax, including partial mocks and chained method behavior.

Laravel's fake helpers. Mail::fake(), Queue::fake(), Event::fake(), Notification::fake(). These are application-level spies, replacing the framework's facades with recording versions for the test. They're convenient for HTTP/feature tests that need to verify "did we send this email?". In Symfony, assertEmailCount() from Symfony\Bundle\FrameworkBundle\Test\MailerAssertionsTrait, which KernelTestCase uses, checks the same thing. Storage::fake() is a fake in the full sense: it swaps the disk for a real local disk rooted in a test directory under storage/framework/testing/disks.

Hand-rolled fakes. Domain ports (Guests, Reservations, EventDispatcher, Clock, Payments) benefit from a real fake implementation in App\Testing. Build them once, reuse across the suite.

Test data builders

Builders sit in this lesson because they set up the objects that doubles work with: the reservations a fake stores and a handler loads.

Every constructor example so far in this lesson spells out its inputs by hand. A test data builder is the fix for objects with many fields: a class with sensible defaults for every field, named methods for the variations a given test cares about, and a build() call that returns the finished object. It's the Builder pattern applied to test setup. The BDD lesson builds RoomBuilder and RatePlanBuilder the same way. Here's the shape, built for the Reservation from the Named Constructors and Repository lessons. The builder calls Reservation::request(), which starts a reservation as Pending. For any other status it calls Reservation::reconstitute(), the public named constructor that rebuilds a reservation from a row. RoomId wraps an integer and GuestId a UUID string, so the builder's do too:

PHP
<?php declare(strict_types=1); namespace App\Testing; use App\Billing\Currency; use App\Billing\Money; use App\Booking\GuestCount; use App\Booking\GuestId; use App\Booking\RoomId; use App\Reservations\DateRange; use App\Reservations\Reservation; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use Carbon\CarbonImmutable; use DateTimeImmutable; final class ReservationBuilder { private RoomId $roomId; private GuestId $guestId; private DateRange $stayDates; private GuestCount $guestCount; private Money $price; private ReservationStatus $status; private function __construct() { $this->roomId = new RoomId(101); $this->guestId = GuestId::next(); $this->stayDates = DateRange::ofNights(CarbonImmutable::parse('2026-06-01'), 2); $this->guestCount = new GuestCount(adults: 2, children: 0); $this->price = Money::fromCents(20000, Currency::usd()); $this->status = ReservationStatus::Pending; } public static function new(): self { return new self(); } public function forRoom(RoomId $roomId): self { $clone = clone $this; $clone->roomId = $roomId; return $clone; } public function checkingInOn(DateTimeImmutable $date): self { $clone = clone $this; $clone->stayDates = DateRange::ofNights(CarbonImmutable::instance($date), 2); return $clone; } public function withStatus(ReservationStatus $status): self { $clone = clone $this; $clone->status = $status; return $clone; } public function build(): Reservation { if ($this->status === ReservationStatus::Pending) { return Reservation::request( guestId: $this->guestId, roomId: $this->roomId, stayDates: $this->stayDates, guestCount: $this->guestCount, quotedPrice: $this->price, ); } return Reservation::reconstitute([ 'id' => ReservationId::next()->value, 'guest_id' => $this->guestId->value, 'room_id' => $this->roomId->value, 'check_in' => $this->stayDates->checkIn->format('Y-m-d'), 'check_out' => $this->stayDates->checkOut->format('Y-m-d'), 'adults' => $this->guestCount->adults, 'children' => $this->guestCount->children, 'price_cents' => $this->price->amountInCents, 'currency' => $this->price->currency->isoCode, 'status' => $this->status->value, ]); } }

Lesson 25's handler test builds Reservation through the public constructor from the Domain Events lesson instead, a second shape the course uses. Only the Named Constructors shape has status(), which pendingCheckInsOn reads, so this builder follows the one the repositories persist.

A test that needs a reservation for a specific room writes exactly that:

PHP
<?php declare(strict_types=1); namespace Tests\Reservations; use App\Booking\RoomId; use App\Testing\ReservationBuilder; use PHPUnit\Framework\TestCase; final class ReservationTest extends TestCase { public function test_a_reservation_for_a_specific_room(): void { $reservation = ReservationBuilder::new() ->forRoom(new RoomId(14)) ->build(); $this->assertSame(14, $reservation->roomId->value); } }

Inline setup buries the point of a test under fields it doesn't care about; a reader has to work out which of the constructor arguments the assertion actually depends on. A builder answers that question by naming only the ones that do.

Pitfalls

A few common mistakes:

Mock all the things. A handler test with seven mocks, each with three expectations, is a test that documents the implementation and leaves the behavior unchecked. The first refactor breaks it.

Stubbing what you should fake. Building a stub that returns five different values for five different inputs is a poor man's fake. Build the actual fake; it'll be cleaner and more reusable.

Spies that double as stubs. A spy is for recording. If your spy also has a setNextResponse(...) method, it's becoming a stub-spy hybrid. Sometimes that's fine, but be aware that you've left "pure spy" territory.

Asserting on private methods. Mocking a private method (or testing a class through reflection to mock its internals) tests the implementation instead of the behavior. The class is doing too much; split it.

Fakes that don't match real behavior. An InMemoryGuests that ignores constraints the real EloquentGuests enforces is lying to the test.

Forgetting to assert. A spy that records calls but the test never reads is dead weight. A mock that's set up but no assertion forces verification is the same. Make sure the test actually checks the recording.

The one thing to remember

Most "we mocked it" should be "we faked it" or "we spied on it". Reach for fakes first; reach for spies when you need to verify side effects; reach for mocks only when the call protocol is genuinely part of the contract.

Course Content