Mocks and test doubles

suggest change

A unit test should check one class without pulling in its database, mail server, payment provider or system clock. You do that by giving the class a test double: an object that stands in for a real dependency and has the same type.

Test doubles only work well when the class receives its dependencies from the outside, usually through the constructor (see dependency injection), and when those dependencies have interfaces.

The examples below test this service:

<?php
declare(strict_types=1);

interface PaymentGateway
{
    /** Charges the card and returns a transaction id. */
    public function charge(string $customerId, int $amountCents): string;
}

interface Mailer
{
    public function send(string $to, string $subject, string $body): void;
}

final class PaymentFailed extends RuntimeException {}

final class OrderService
{
    public function __construct(
        private PaymentGateway $gateway,
        private Mailer $mailer,
    ) {}

    public function checkout(string $customerId, string $email, int $amountCents): string
    {
        if ($amountCents <= 0) {
            throw new InvalidArgumentException('Amount must be positive');
        }

        try {
            $txId = $this->gateway->charge($customerId, $amountCents);
        } catch (PaymentFailed $e) {
            $this->mailer->send($email, 'Payment failed', $e->getMessage());
            throw $e;
        }

        $this->mailer->send($email, 'Order confirmed', "Transaction $txId");
        return $txId;
    }
}

Kinds of test doubles

The names come from Gerard Meszaros' book xUnit Test Patterns:

Kind What it does Typical use
Dummy Passed in only to satisfy a parameter; never used A constructor argument the test doesn't touch
Stub Returns canned values Control the input the code under test receives
Fake A working but simplified implementation (e.g. in-memory repository) Realistic behaviour without infrastructure
Spy Records calls so the test can inspect them afterwards Verify output after the fact
Mock Pre-programmed with expectations that are verified automatically Verify that a specific call happens

Rule of thumb: use a stub when you care about what the dependency returns, and a mock when you care about how it is called. Don't verify calls that are not part of the behaviour you are testing; it makes tests brittle.

Stubs with createStub()

createStub() creates an object implementing the interface (or extending the class). Every method returns a default value for its return type ('' for string, 0 for int, null for nullable types, an empty array, or another stub for object types) until you configure it:

<?php
use PHPUnit\Framework\TestCase;

final class OrderServiceTest extends TestCase
{
    public function testCheckoutReturnsTransactionId(): void
    {
        $gateway = $this->createStub(PaymentGateway::class);
        $gateway->method('charge')->willReturn('tx-123');

        $mailer = $this->createStub(Mailer::class); // used as a dummy here

        $service = new OrderService($gateway, $mailer);

        $this->assertSame('tx-123', $service->checkout('cust-1', 'a@example.com', 5000));
    }
}

Ways to configure what a stubbed method does:

<?php
// the same value every time
$stub->method('charge')->willReturn('tx-1');

// consecutive values: 'tx-1' on the first call, then 'tx-2', then 'tx-3'
$stub->method('charge')->willReturn('tx-1', 'tx-2', 'tx-3');

// a value chosen by arguments: each row is [arg1, arg2, ..., return value]
$stub->method('charge')->willReturnMap([
    ['cust-1', 100, 'tx-a'],
    ['cust-2', 200, 'tx-b'],
]);

// compute the result from the arguments
$stub->method('charge')->willReturnCallback(
    fn (string $customerId, int $amount): string => "tx-$customerId-$amount"
);

// throw instead of returning
$stub->method('charge')->willThrowException(new PaymentFailed('Card declined'));

// other helpers: willReturnArgument(0), willReturnSelf() for fluent APIs

With willReturnMap(), a call whose arguments don't match any row returns null (a TypeError for a non-nullable return type), which doesn't tell you which row was missing. willReturnCallback() with a match that throws on unknown input is often clearer.

For a stub that only needs fixed return values you can use createConfiguredStub():

<?php
$gateway = $this->createConfiguredStub(PaymentGateway::class, [
    'charge' => 'tx-123',
]);

Mocks with createMock() and expects()

A mock verifies interaction. expects() takes an invocation count matcher and with() takes constraints for each argument. PHPUnit checks the expectations automatically when the test ends:

<?php
public function testSendsConfirmationEmail(): void
{
    $gateway = $this->createStub(PaymentGateway::class);
    $gateway->method('charge')->willReturn('tx-123');

    $mailer = $this->createMock(Mailer::class);
    $mailer->expects($this->once())
        ->method('send')
        ->with(
            'a@example.com',                      // plain value means equalTo()
            'Order confirmed',
            $this->stringContains('tx-123'),
        );

    $service = new OrderService($gateway, $mailer);
    $service->checkout('cust-1', 'a@example.com', 5000);
}

Invocation count matchers: once(), never(), exactly($n), atLeastOnce(), atLeast($n), atMost($n) and any().

Useful argument constraints: equalTo(), identicalTo(), anything(), isInstanceOf(Foo::class), greaterThan(), stringContains(), matchesRegularExpression() and callback(). callback() gets the actual argument and must return true if it is acceptable:

<?php
$gateway = $this->createMock(PaymentGateway::class);
$gateway->expects($this->once())
    ->method('charge')
    ->with('cust-1', $this->callback(fn (int $amount): bool => $amount > 0 && $amount % 100 === 0))
    ->willReturn('tx-1');

Testing that a dependency is not called, and testing the error path:

<?php
public function testRejectsNonPositiveAmountWithoutCharging(): void
{
    $gateway = $this->createMock(PaymentGateway::class);
    $gateway->expects($this->never())->method('charge');

    $service = new OrderService($gateway, $this->createStub(Mailer::class));

    $this->expectException(InvalidArgumentException::class);
    $service->checkout('cust-1', 'a@example.com', 0);
}

public function testNotifiesCustomerWhenPaymentFails(): void
{
    $gateway = $this->createStub(PaymentGateway::class);
    $gateway->method('charge')->willThrowException(new PaymentFailed('Card declined'));

    $mailer = $this->createMock(Mailer::class);
    $mailer->expects($this->once())
        ->method('send')
        ->with('a@example.com', 'Payment failed', 'Card declined');

    $service = new OrderService($gateway, $mailer);

    $this->expectException(PaymentFailed::class);
    $service->checkout('cust-1', 'a@example.com', 5000);
}

Prefer createStub() whenever you don't call expects(). Configuring expectations on a test stub was deprecated in PHPUnit 11 and is not possible in PHPUnit 12, and recent PHPUnit 12 releases report a notice when a mock object is created but no expectations are configured on it.

Different arguments on consecutive calls

withConsecutive() and the at() matcher were deprecated in PHPUnit 9 and removed in PHPUnit 10. The replacement is willReturnCallback() combined with the invocation counter of the matcher:

<?php
public function testSendsTwoEmails(): void
{
    $mailer = $this->createMock(Mailer::class);
    $matcher = $this->exactly(2);

    $mailer->expects($matcher)
        ->method('send')
        ->willReturnCallback(function (string $to, string $subject) use ($matcher): void {
            match ($matcher->numberOfInvocations()) {
                1 => $this->assertSame('Welcome', $subject),
                2 => $this->assertSame('Order confirmed', $subject),
            };
        });

    // ... code that sends a welcome email and then a confirmation
}

Often a cleaner option is to record the calls and assert on the whole list at the end, as shown in the spy section below.

Hand-written fakes and spies

You don't need a framework for test doubles. A small class implementing the interface is often easier to read than a heavily configured mock, and it can be reused across tests:

<?php
final class InMemoryMailer implements Mailer
{
    /** @var list<array{to: string, subject: string, body: string}> */
    public array $sent = [];

    public function send(string $to, string $subject, string $body): void
    {
        $this->sent[] = ['to' => $to, 'subject' => $subject, 'body' => $body];
    }
}

final class FakePaymentGateway implements PaymentGateway
{
    private int $next = 1;

    /** @var array<string, int> charged amounts by transaction id */
    public array $charges = [];

    public function __construct(private array $declinedCustomers = []) {}

    public function charge(string $customerId, int $amountCents): string
    {
        if (in_array($customerId, $this->declinedCustomers, true)) {
            throw new PaymentFailed('Card declined');
        }
        $txId = 'tx-' . $this->next++;
        $this->charges[$txId] = $amountCents;
        return $txId;
    }
}

InMemoryMailer is a spy: the test runs the code, then inspects what was recorded. This style ("arrange, act, assert") keeps assertions at the end of the test:

<?php
public function testCheckoutWithFakes(): void
{
    $gateway = new FakePaymentGateway(declinedCustomers: ['bad-customer']);
    $mailer = new InMemoryMailer();
    $service = new OrderService($gateway, $mailer);

    $txId = $service->checkout('cust-1', 'a@example.com', 5000);

    $this->assertSame(['tx-1' => 5000], $gateway->charges);
    $this->assertCount(1, $mailer->sent);
    $this->assertSame('Order confirmed', $mailer->sent[0]['subject']);
    $this->assertStringContainsString($txId, $mailer->sent[0]['body']);
}

For one-off doubles, an anonymous class avoids a separate file:

<?php
$gateway = new class implements PaymentGateway {
    public function charge(string $customerId, int $amountCents): string
    {
        return 'tx-fixed';
    }
};

Fakes are a good fit for repositories (an array instead of a database), clocks (PSR-20 ClockInterface returning a fixed DateTimeImmutable) and caches. A clock interface is the standard way to make code that uses "now" testable, because new DateTimeImmutable() inside a method can't be replaced.

What can and can't be doubled

Mockery

Mockery is a popular alternative mocking library (composer require --dev mockery/mockery) used by default in Laravel. Its API reads more like English and it supports spies natively:

<?php
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;

final class OrderServiceMockeryTest extends TestCase
{
    use MockeryPHPUnitIntegration; // verifies expectations and calls Mockery::close()

    public function testCheckout(): void
    {
        $gateway = Mockery::mock(PaymentGateway::class);
        $gateway->shouldReceive('charge')
            ->once()
            ->with('cust-1', 5000)
            ->andReturn('tx-123');

        $mailer = Mockery::spy(Mailer::class);

        $service = new OrderService($gateway, $mailer);
        $service->checkout('cust-1', 'a@example.com', 5000);

        $mailer->shouldHaveReceived('send')
            ->with('a@example.com', 'Order confirmed', Mockery::pattern('/tx-123/'))
            ->once();
    }
}

A Mockery mock throws on any call that was not set up with shouldReceive(), while a spy accepts every call and lets you assert afterwards. andThrow(new PaymentFailed(...)) makes a method throw, and andReturnUsing(fn (...) => ...) computes the return value.

Pick one library per project; mixing PHPUnit doubles and Mockery in the same test suite works but makes tests harder to read.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents