Skip to content

Lesson 4 of 9 · 25m

Mocking Boundaries, Not Everything in Reach

How to use PHPUnit test doubles at ports and interfaces, when mocks make tests worse, and why interaction assertions are a last resort.

Most mock-heavy tests are not unit tests. They are reimplementations of the production object graph written in expectation syntax. You change a private implementation detail, five tests break, and the team concludes tests are expensive. The tests were expensive because they knew too much.

Mock the boundary you own

A good mock sits at an architectural port: payment gateway, message bus, clock, object storage, remote API client. Those dependencies are slow, non-deterministic, external, or operationally dangerous.

interface PaymentGateway
{
    public function charge(Customer $customer, Money $amount): ChargeResult;
}

$gateway = $this->createMock(PaymentGateway::class);
$gateway->method('charge')->willReturn(ChargeResult::success('ch_123'));

$order = (new CheckoutService($gateway, new InMemoryOrderRepository()))
    ->checkout($this->orderFixture());

self::assertSame(OrderStatus::Paid, $order->status());

The test proves your orchestration logic. It does not prove Stripe accepts the payload; that belongs in a gateway integration test.

Prefer state assertions over interaction assertions

This style is seductive and usually wrong:

$mailer->expects(self::once())
    ->method('send')
    ->with(self::anything());

Now the test verifies the implementation did exactly what the implementation does. It cannot tell you whether the user received the right email. Use interaction assertions only when the interaction itself is the contract: exactly-once publishing, cache invalidation, or a call that must not happen.

Fakes often beat mocks

final class FakeClock implements Clock
{
    public function __construct(private DateTimeImmutable $now) {}
    public function now(): DateTimeImmutable { return $this->now; }

    public function advance(DateInterval $interval): void
    {
        $this->now = $this->now->add($interval);
    }
}

A fake clock can simulate time passing. A mock clock can only answer canned timestamps. One models the domain; the other models a method call.

Do not mock what you do not own

Mocking a third-party SDK class reproduces your guesses about that SDK. When the vendor changes behavior, your green tests are still green. Wrap third-party clients behind a narrow interface you own, mock your interface in application tests, and integration-test the adapter against the real client or a recorded contract.

Field notes

  • Mock interfaces and small ports; concrete internal classes couple tests to constructors and private structure. createStub returns values; createMock can verify interactions.
  • If setup takes longer than the test body, the unit is too big. Never assert a call merely because production code makes it — assert an outcome.

Was this lesson helpful?

Sign in to rate