Test Doubles Explained: Mocks, Stubs, Fakes and Spies

When I first joined a team that took automated testing seriously, I heard the terms mock, stub, fake, and spy used almost interchangeably. Someone would say "just mock the database" when they actually meant building an in-memory fake, or "stub this API call" when they were really verifying that a specific method was called. That loose language creates real problems, because each type of test double solves a different problem and misusing them leads to tests that are either brittle, misleading, or painfully slow. Understanding the distinctions, which were originally cataloged by Gerard Meszaros in xUnit Test Patterns and later popularized by Martin Fowler, will make your test suite more maintainable and your feedback loops much faster. In this article I will break down what each double is, when it earns its keep, and how I decide which one to reach for in real projects.

Why Your Unit Tests Need Stand-Ins for Real Dependencies

A unit test should give you a fast, deterministic answer to a simple question: does this piece of logic behave correctly? The moment that logic reaches out to a database, a payment gateway, the file system, or even a complex collaborator class inside your own codebase, that determinism disappears. In my experience, the first sign you need a test double is not a purist architectural debate, but practical pain: tests that take seconds instead of milliseconds, that fail randomly in CI, or that require elaborate setup just to exercise a single conditional branch.

Think of a function that calculates a discount and then calls emailService.sendReceipt() and paymentGateway.charge(). To test the discount calculation, you do not need to send a real email or hit a real Stripe endpoint. You need to isolate the unit under test so that only the discount logic can cause a failure. Everything else gets replaced by a stand-in that you control. That stand-in is a test double, a direct analogy to a stunt double in film.

When a Real Collaborator Hurts Feedback Loops

I have seen suites where a single test file spun up a full PostgreSQL instance for every test case, even when the code under test was just formatting a query string. The result was a suite that took 12 minutes to run locally. Developers stopped running it. If you are writing tests that integrate with real infrastructure, that is valuable work, but it belongs in a dedicated integration layer. For more on that separation, see Integration Testing with Testcontainers: Real Databases in Your Test Suite, which covers when real databases add confidence instead of drag. For everything else, a double keeps the unit test focused on logic, not infrastructure.

The Vocabulary Problem: Dummy vs Everything Else

Part of the confusion is that all test doubles look like fakes at first glance. Technically, a dummy is the simplest double: an object that is passed around but never actually used, just to satisfy a parameter list. You will use dummies less often in modern languages with optional dependencies, but the idea matters because it clarifies the taxonomy. Stubs provide answers, mocks verify interactions, spies record what happened, and fakes actually work. If you can name which job you need, you will pick the right tool.

Stubs: Feeding Canned Answers to Your Code Under Test

A stub is the simplest useful double. It provides canned answers to calls made during the test and generally does not care whether or how it was called. Its purpose is to control the indirect inputs to your system under test (SUT). In my experience, stubs are the double I reach for most often, because most units need to pull data from somewhere before they can do their job.

A classic example is a repository or a feature flag service. Your code asks, "what is the current user?" or "is this feature enabled?" and then branches accordingly. You do not want to set up thousands of rows in a database to test both branches; you want to stub the response. A stub lets you simulate edge cases that are hard to produce with real collaborators, like a timeout, an empty result set, or a specific error code from a third-party API.

Stub in Action: Controlling Indirect Inputs

Here is a Python example using the standard library. I am testing a function that applies a discount if a user is flagged as premium. Instead of querying a real user service, I stub the lookup.

from unittest.mock import Mock

# The code under test
def calculate_discount(user_id, user_service, price):
    user = user_service.get_user(user_id)
    if user and user.get("is_premium"):
        return price * 0.8
    return price

# Test with a stub
def test_premium_users_get_discount():
    # Stub: canned answer, no behavior verification
    stub_service = Mock()
    stub_service.get_user.return_value = {"id": 42, "is_premium": True}
    
    result = calculate_discount(42, stub_service, 100.0)
    
    assert result == 80.0

def test_regular_users_pay_full_price():
    stub_service = Mock()
    stub_service.get_user.return_value = {"id": 99, "is_premium": False}
    
    result = calculate_discount(99, stub_service, 100.0)
    
    assert result == 100.0

Notice that we never verify that get_user was called a certain number of times. We only care about the answer it returned and how the SUT reacted. That is the hallmark of a stub. According to the Python Documentation for unittest.mock, setting return_value on a Mock is essentially using it as a stub, which illustrates how one library object can play multiple roles depending on how you use it. I keep stubs as simple as possible. If a stub starts to contain conditional logic or state, I consider whether a fake would be clearer.

Stubs are excellent for state verification: you exercise the SUT and then assert on its return value or its final state. They keep tests readable because the setup maps directly to "when the collaborator returns X, the SUT should do Y."

Mocks: Verifying How Your Code Talks to Its Collaborators

If stubs are about controlling inputs, mocks are about verifying outputs that are not returned directly. A mock is a double that is pre-programmed with expectations about how it should be called, and it will fail the test if those expectations are not met. This is behavior verification, as opposed to state verification.

I've found that mocks are most appropriate when the important effect of your code is a side effect. Sending an email, publishing an event to a message queue, writing to a log, or charging a credit card does not change the return value of a function in a way you can easily assert on, but you still need to know that it happened, with the correct arguments, exactly once.

The danger with mocks is overuse. In one codebase I inherited, nearly every test mocked every collaborator, which meant the tests were mirrors of the implementation. Renaming an internal method call broke 30 tests even though the external behavior was unchanged. That is the definition of a brittle test. I now follow a rule: mock only across significant architectural boundaries or when the side effect is the primary responsibility of the unit. Do not mock value objects or stable domain entities.

Mock in Action: Asserting Outgoing Interactions

Consider an order service that must notify a warehouse after payment succeeds. The notification is the important behavior.

from unittest.mock import Mock

class OrderProcessor:
    def __init__(self, payment_gateway, warehouse_api):
        self.payment_gateway = payment_gateway
        self.warehouse_api = warehouse_api

    def place_order(self, order):
        if self.payment_gateway.charge(order.total, order.token):
            self.warehouse_api.reserve(order.items, order.id)
            return True
        return False

def test_successful_order_reserves_inventory():
    mock_gateway = Mock()
    mock_gateway.charge.return_value = True
    mock_warehouse = Mock()
    order = Mock(total=50.0, token="tok_123", items=["widget"], id="ord_1")

    processor = OrderProcessor(mock_gateway, mock_warehouse)
    result = processor.place_order(order)

    assert result is True
    # Behavior verification: did we talk to the collaborator correctly?
    mock_warehouse.reserve.assert_called_once_with(["widget"], "ord_1")
    mock_gateway.charge.assert_called_once_with(50.0, "tok_123")

def test_failed_payment_does_not_reserve():
    mock_gateway = Mock()
    mock_gateway.charge.return_value = False
    mock_warehouse = Mock()
    order = Mock(total=50.0, token="tok_123", items=["widget"], id="ord_1")

    processor = OrderProcessor(mock_gateway, mock_warehouse)
    result = processor.place_order(order)

    assert result is False
    mock_warehouse.reserve.assert_not_called()

Here the assertions on assert_called_once_with and assert_not_called are what make these doubles mocks. The test would pass even if the return value was correct but the warehouse call was missing, so we need that explicit check. This distinction between stubs (which we query after the fact) and mocks (which self-verify) is subtle but important for maintainability. When you find yourself mocking three or four collaborators to test a single method, it is often a sign that the class has too many responsibilities and should be refactored.

Spies: The Observant Wrapper Around Real Logic

A spy is a hybrid. Unlike a stub or a mock that completely replaces a collaborator, a spy wraps the real implementation and records information about how it was called while optionally still executing the real logic. In practice, spies are the least discussed double but I reach for them when I want to observe side effects without throwing away useful real behavior.

Spies are particularly handy when the real object is lightweight and has valuable logic you want to keep, but you still need to confirm interactions. For example, you might have an in-memory cache that you want to function normally during the test, but you want to verify that a particular method attempted to write to it. Or you might spy on a logger to ensure a warning was emitted without silencing all logging.

Spy in Action: Recording Without Fully Replacing

In JavaScript, spies are a core feature of many test frameworks, but you can build one manually in any language. The MDN Web Docs describe similar patterns when wrapping native APIs for testing. Here is a Python-style manual spy that wraps a real notifier but records calls:

class EmailService:
    def send(self, to, subject):
        # real logic: format and queue email
        print(f"Queueing email to {to}: {subject}")
        return True

class EmailSpy(EmailService):
    def __init__(self):
        self.calls = []
        super().__init__()

    def send(self, to, subject):
        self.calls.append((to, subject))
        # still execute real logic
        return super().send(to, subject)

def test_signup_sends_welcome_email():
    spy = EmailSpy()
    
    def signup(email, service):
        # simplified SUT
        if "@" in email:
            service.send(email, "Welcome!")
            return True
        return False

    result = signup("ada@example.com", spy)

    assert result is True
    assert len(spy.calls) == 1
    assert spy.calls[0] == ("ada@example.com", "Welcome!")

This spy preserves the real send behavior, which is useful if other parts of the test depend on its return value or side effects, but it also gives you a simple list of calls to assert on. Most mocking libraries provide a spy mode directly. In Python's unittest.mock, a Mock(wraps=real_object) creates a spy. In Jest or Sinon, jest.spyOn() does the same.

I've found that spies reduce the risk of false positives that pure mocks can introduce. Because the real code still runs, you are less likely to have a mock whose configured behavior drifts from reality. The trade-off is that spies couple your test slightly more to the real implementation, so I use them when the collaborator is fast and deterministic, not when it hits the network.

Fakes: Lightweight Working Implementations for Faster Feedback

A fake is fundamentally different from the other three. It is not a configured expectation but a real, working implementation that is unsuitable for production. The classic example is an in-memory repository that implements the same interface as your Postgres repository but stores data in a dictionary. It has real logic, it actually works, and it can be used across many tests without per-test configuration.

Fakes shine when a stub would require too much setup or a mock would be too brittle. If your domain logic needs to query, filter, and persist objects, stubbing every possible query response becomes tedious and masks how the objects interact. An in-memory fake lets you exercise richer workflows: create two users, update one, then assert that the correct one was returned. In my experience, a well-written fake is the most maintainable double for repository-like abstractions.

Fake vs Mock: When to Build a Real Alternative

The decision to build a fake comes down to complexity and reuse. Building a fake has an upfront cost, but it pays off if you use it in dozens of tests. I will write a fake for a UserRepository, a FileStorage abstraction, or a clock service, but I would never write a fake for a third-party payment gateway, because reproducing its edge cases and failure modes accurately is too hard. For those, a stub or mock that models just the one interaction you need is more pragmatic.

class FakeUserRepository:
    def __init__(self):
        self.store = {}

    def save(self, user):
        self.store[user["id"]] = user

    def find_by_id(self, user_id):
        return self.store.get(user_id)

    def find_premium_users(self):
        return [u for u in self.store.values() if u.get("is_premium")]

# SUT that uses the repository
def count_premium_users(repo):
    return len(repo.find_premium_users())

def test_counts_premium_users_with_fake():
    repo = FakeUserRepository()
    repo.save({"id": 1, "is_premium": True})
    repo.save({"id": 2, "is_premium": False})
    repo.save({"id": 3, "is_premium": True})

    assert count_premium_users(repo) == 2

def test_fake_isolates_between_tests():
    repo = FakeUserRepository()  # fresh instance, no leftover state
    repo.save({"id": 1, "is_premium": False})
    assert count_premium_users(repo) == 0

Notice that the test never configures return values per call. It simply uses the fake as it would the real repository. This makes tests more readable and less coupled to implementation details. The downside is that a fake can hide integration bugs if its behavior diverges from the production implementation. I mitigate this by keeping fakes deliberately simple and by having a small number of contract tests that run the same assertions against both the fake and the real implementation in CI.

Choosing the Right Test Double Without Over-Mocking Your Suite

With four options, the practical question is how to choose quickly without overthinking. I use a simple heuristic that has kept my suites balanced over several years. First, ask what you are trying to prove. If you need to control what the SUT sees, use a stub. If you need to prove the SUT called out correctly, use a mock. If you want to observe calls but keep real behavior, use a spy. If you need a working stand-in that will be reused widely, invest in a fake.

Second, consider the cost of being wrong. Mocks that verify internal method names are the most likely to become brittle. If you are mocking a stable, public interface at an architectural boundary, like an email gateway or a queue publisher, the coupling is low and the verification is valuable. If you are mocking a private helper method inside the same module, the coupling is high and a state-based test with a stub or fake will be more resilient.

This is also where broader quality strategies matter. A suite full of mocks can still have high coverage and low confidence. Combining well-chosen doubles with techniques described in Mutation Testing: Why 100% Code Coverage Does Not Mean Bug-Free helps you find assertions that do not actually protect behavior, and using fakes for domain repositories pairs well with property-based checks as discussed in Property-Based Testing: Finding Bugs That Unit Tests Miss.

Test Double Purpose Verifies When to Prefer It
Stub Provide canned answers to drive the SUT down a path State / return value of SUT Controlling indirect inputs; simulating data or error responses
Mock Expect and verify outgoing interactions Behavior / interaction history Side effects at boundaries: emails, payments, events
Spy Wrap real object and record calls Both state and behavior, with real logic executed Observing calls without losing real implementation
Fake Lightweight working implementation State through realistic usage Repositories, storage, clocks; reused across many tests
Dummy Satisfy parameter list, never used Nothing Filling required arguments that the SUT does not touch

My Rules of Thumb After Years of Brittle Tests

I limit mocks to one or two per test, and I never mock the class I am testing. I prefer fakes for persistence-like abstractions and stubs for read-only queries. I use spies when a framework provides them cheaply, especially for logging or caching layers. And I keep a strict separation: unit tests with doubles should run in milliseconds with no I/O, while integration tests with real collaborators live in a separate, slower suite that I run less frequently. That separation preserves fast feedback without sacrificing confidence.

Frequently Asked Questions

What is the main difference between a mock and a stub?

A stub controls inputs by returning canned data and is used for state verification: you call the SUT and assert on what it returns. A mock verifies outputs by setting expectations about how it should be called and is used for behavior verification: you assert that the SUT called the mock with the expected arguments. In practice, many libraries like Python's unittest.mock provide an object that can act as either, so the difference is in how you use it, not the class name.

Do I need a mocking framework to use test doubles?

No. You can hand-write any double with plain classes, which I often do for fakes and simple stubs. Frameworks simply reduce boilerplate for mocks and spies by generating objects that record calls and verify expectations. If you are starting out, try writing a manual stub and a manual fake first; you will better understand what the framework is automating and avoid relying on complex mock configuration when a simple hand-written alternative would be clearer.

When should I use a fake instead of a mock?

Use a fake when several tests need realistic, stateful behavior from a collaborator and configuring stubs or mocks per test would be repetitive. Fakes are ideal for repositories, caches, or file systems where you can implement a fast in-memory version that obeys the same interface as the production code. Avoid fakes for third-party services that are hard to replicate faithfully; there a focused stub or mock for the single interaction you need is safer.

Are tests that use mocks more brittle than other tests?

They can be, if you mock every internal interaction. Every mocked call couples the test to an implementation detail, so renaming a method or changing call order can break tests even when behavior is still correct. To keep mocks from making your suite brittle, mock only at stable architectural boundaries, prefer state-based assertions when possible, and keep the number of mocked interactions per test small. Pairing this discipline with code review practices, as in effective review checklists, helps catch over-mocking early.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards