StackPractices
intermediate By Mathias Paulenko

Test Double: Replace Dependencies with Stubs, Spies, Fakes

How to use test doubles to isolate units under test. Covers stubs, spies, fakes, mocks, and dummy objects with examples in Python, JavaScript, and Java.

Topics: testing

Overview

A test double is any object that stands in for a real dependency in a test. Gerard Meszaros coined the term in xUnit Test Patterns and split it into five kinds: dummy, stub, spy, fake, and mock. They do different jobs — a dummy fills a parameter slot, a stub returns canned answers, a spy records calls, a fake is a simplified working implementation, and a mock verifies expectations. Picking the right one keeps tests focused, fast, and immune to external flakiness.

When to Use

  • Isolating a unit from databases, APIs, file systems, or message queues
  • Triggering error paths you can’t easily reproduce with the real dependency
  • Replacing slow I/O with in-memory doubles so the suite stays fast
  • Checking that a call happened — “did send_email get the right address?”
  • Depending on services that aren’t reachable from CI

When NOT to Use

  • Integration tests — real dependencies are the point there
  • Simple, fast dependencies — doubling a pure function adds noise
  • A double more complex than the real thing — just use the real one
  • Behavior you don’t own — a mock of an external API can’t tell you when that API changes

Solution

Types of Test Doubles

TypePurposeExample
DummyPassed but never usedNull logger parameter
StubReturns canned responsesgetUser() always returns {id: 1}
SpyRecords calls for later verificationCaptures send_email("alice@x.com")
FakeWorking but simplified implementationIn-memory database instead of PostgreSQL
MockPre-programmed expectations”Expect save() called exactly once”

Dummy — Placeholder object

# Python — dummy logger passed but never used
class DummyLogger:
    def info(self, msg): pass
    def error(self, msg): pass
    def warning(self, msg): pass

class OrderProcessor:
    def __init__(self, logger):
        self.logger = logger

    def process(self, order):
        # logger is never called in this test scenario
        return order.total * 1.1

def test_process_order():
    processor = OrderProcessor(DummyLogger())
    result = processor.process(Order(total=100))
    assert result == 110.0

Stub — Returns canned responses

# Python — stub for a user repository
class UserRepositoryStub:
    def __init__(self, user=None):
        self.user = user

    def find_by_id(self, user_id):
        return self.user

    def save(self, user):
        pass

def test_get_user_name():
    repo = UserRepositoryStub(user=User(id=1, name="Alice"))
    service = UserService(repo)
    assert service.get_name(1) == "Alice"

def test_get_user_name_not_found():
    repo = UserRepositoryStub(user=None)
    service = UserService(repo)
    with pytest.raises(NotFoundError):
        service.get_name(999)
// JavaScript — stub with jest
const userRepo = {
  findById: jest.fn().mockResolvedValue({ id: 1, name: 'Alice' }),
  save: jest.fn().mockResolvedValue(true),
};

const service = new UserService(userRepo);

test('getUserName returns name', async () => {
  const name = await service.getUserName(1);
  expect(name).toBe('Alice');
  expect(userRepo.findById).toHaveBeenCalledWith(1);
});

Spy — Records interactions for verification

# Python — spy with unittest.mock
from unittest.mock import MagicMock

def test_email_sent_on_order():
    email_service = MagicMock()
    notifier = OrderNotifier(email_service)

    notifier.notify_order_completed(Order(id=42, customer_email="alice@x.com"))

    # Verify the spy recorded the call
    email_service.send.assert_called_once_with(
        to="alice@x.com",
        subject="Order #42 completed",
    )

def test_email_spy_records_multiple_calls():
    email_service = MagicMock()
    notifier = OrderNotifier(email_service)

    notifier.notify_order_completed(Order(id=1, customer_email="a@x.com"))
    notifier.notify_order_completed(Order(id=2, customer_email="b@x.com"))

    assert email_service.send.call_count == 2
    calls = email_service.send.call_args_list
    assert calls[0].kwargs['to'] == "a@x.com"
    assert calls[1].kwargs['to'] == "b@x.com"
// JavaScript — spy with jest
const emailService = {
  send: jest.fn(),
};

const notifier = new OrderNotifier(emailService);

test('email sent on order completion', () => {
  notifier.notifyOrderCompleted({ id: 42, customerEmail: 'alice@x.com' });

  expect(emailService.send).toHaveBeenCalledTimes(1);
  expect(emailService.send).toHaveBeenCalledWith({
    to: 'alice@x.com',
    subject: 'Order #42 completed',
  });
});

Fake — Simplified working implementation

# Python — fake in-memory repository
class FakeUserRepository:
    def __init__(self):
        self._users = {}
        self._next_id = 1

    def create(self, name, email):
        user = User(id=self._next_id, name=name, email=email)
        self._users[self._next_id] = user
        self._next_id += 1
        return user

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

    def find_by_email(self, email):
        return next((u for u in self._users.values() if u.email == email), None)

    def delete(self, user_id):
        return self._users.pop(user_id, None) is not None

    def count(self):
        return len(self._users)

def test_create_and_find_user():
    repo = FakeUserRepository()
    service = UserService(repo)

    user = service.create_user("Alice", "alice@x.com")
    found = service.get_user(user.id)

    assert found.name == "Alice"
    assert found.email == "alice@x.com"

def test_duplicate_email_rejected():
    repo = FakeUserRepository()
    service = UserService(repo)

    service.create_user("Alice", "alice@x.com")
    with pytest.raises(DuplicateEmailError):
        service.create_user("Bob", "alice@x.com")
// Java — fake in-memory repository
public class FakeUserRepository implements UserRepository {
    private final Map<Long, User> users = new HashMap<>();
    private long nextId = 1;

    @Override
    public User create(String name, String email) {
        User user = new User(nextId, name, email);
        users.put(nextId, user);
        nextId++;
        return user;
    }

    @Override
    public User findById(long id) {
        return users.get(id);
    }

    @Override
    public Optional<User> findByEmail(String email) {
        return users.values().stream()
            .filter(u -> u.getEmail().equals(email))
            .findFirst();
    }

    @Override
    public boolean delete(long id) {
        return users.remove(id) != null;
    }

    @Override
    public long count() {
        return users.size();
    }
}

// Test using the fake
@Test
void testCreateAndFindUser() {
    UserRepository repo = new FakeUserRepository();
    UserService service = new UserService(repo);

    User user = service.createUser("Alice", "alice@x.com");
    User found = service.getUser(user.getId());

    assertEquals("Alice", found.getName());
    assertEquals("alice@x.com", found.getEmail());
}

Mock — Pre-programmed expectations

// Java — mock with Mockito
import static org.mockito.Mockito.*;

@Test
void testOrderProcessingCallsRepository() {
    // Create mock
    OrderRepository repo = mock(OrderRepository.class);
    PaymentGateway gateway = mock(PaymentGateway.class);
    OrderProcessor processor = new OrderProcessor(repo, gateway);

    // Program expectations
    when(repo.findById(1L)).thenReturn(new Order(1L, 100.0));
    when(gateway.charge(anyString(), eq(100.0))).thenReturn(true);

    // Execute
    boolean result = processor.processOrder(1L, "card-token-123");

    // Verify interactions
    assertTrue(result);
    verify(repo).findById(1L);
    verify(repo).save(argThat(order -> order.getStatus() == OrderStatus.COMPLETED));
    verify(gateway, times(1)).charge("card-token-123", 100.0);
    verifyNoMoreInteractions(repo, gateway);
}
// JavaScript — mock with jest
const orderRepo = {
  findById: jest.fn(),
  save: jest.fn(),
};
const paymentGateway = {
  charge: jest.fn(),
};

const processor = new OrderProcessor(orderRepo, paymentGateway);

beforeEach(() => {
  jest.clearAllMocks();
});

test('processOrder completes successfully', async () => {
  orderRepo.findById.mockResolvedValue({ id: 1, total: 100.0 });
  paymentGateway.charge.mockResolvedValue(true);

  const result = await processor.processOrder(1, 'card-token-123');

  expect(result).toBe(true);
  expect(orderRepo.findById).toHaveBeenCalledWith(1);
  expect(paymentGateway.charge).toHaveBeenCalledWith('card-token-123', 100.0);
  expect(orderRepo.save).toHaveBeenCalledWith(
    expect.objectContaining({ status: 'COMPLETED' })
  );
});

Choosing the right double

# Decision guide:
# 1. Need to pass something but it's never called? → DUMMY
# 2. Need controlled return values? → STUB
# 3. Need to verify a method was called? → SPY
# 4. Need working but simplified behavior? → FAKE
# 5. Need to assert exact call sequences? → MOCK

# Example: Use a FAKE for repository, SPY for email
class TestOrderService:
    def setup_method(self):
        self.repo = FakeOrderRepository()  # Fake — working implementation
        self.email_service = MagicMock()   # Spy — verify calls
        self.service = OrderService(self.repo, self.email_service)

    def test_order_triggers_email(self):
        order = self.service.create_order(customer_id=1, total=50.0)

        # Verify state with fake
        saved = self.repo.find_by_id(order.id)
        assert saved.status == "PENDING"

        # Verify interaction with spy
        self.email_service.send.assert_called_once()
        call_args = self.email_service.send.call_args
        assert "order" in call_args.kwargs['subject'].lower()

Explanation

flowchart diagram: What does the double do?

The five types differ in what the test asserts against. Stubs and fakes are indirect inputs — the test still checks state or return values. Spies and mocks are indirect outputs — the test checks the calls themselves. That single distinction drives most “mock vs stub” confusion: if your assertion reads like verify(...) or assert_called_with, you’re testing interaction, not behavior.

Interaction-based tests break when implementation details change even though behavior didn’t — that’s over-specification, and it’s why fakes age better than mocks. Martin Fowler covers this trade-off in Mocks Aren’t Stubs, the classic reference alongside Meszaros’s taxonomy. For the broader test-suite structure, see the Test Pyramid Pattern; if the double is an HTTP service, the Mock Server Pattern is usually a better fit than in-process doubles.

Variants

Auto-mocking with dependency injection

# Python — pytest with fixture-based auto-mocking
@pytest.fixture
def mock_repo():
    return MagicMock(spec=UserRepository)

@pytest.fixture
def service(mock_repo):
    return UserService(mock_repo)

def test_get_user(service, mock_repo):
    mock_repo.find_by_id.return_value = User(id=1, name="Alice")
    result = service.get_user(1)
    assert result.name == "Alice"

Mock vs Fake for database tests

# Approach 1: Mock the repository (fast but brittle)
def test_with_mock():
    repo = MagicMock()
    repo.find_by_id.return_value = User(id=1, name="Alice")
    # Test breaks if implementation calls repo differently

# Approach 2: Fake repository (fast and resilient)
def test_with_fake():
    repo = FakeUserRepository()
    repo.create("Alice", "alice@x.com")
    # Test focuses on behavior, not implementation details

Partial mock — spy on real object

# Python — partial mock: real object with one method spied
from unittest.mock import patch

def test_with_partial_mock():
    service = RealOrderService(real_repo, real_email)

    # Only mock the email call, everything else is real
    with patch.object(service, 'send_notification') as mock_send:
        service.process_order(Order(id=1, total=100))
        mock_send.assert_called_once()

Test double with dependency injection container

// Java — Spring test with mocked beans
@SpringBootTest
class OrderServiceTest {

    @Autowired
    private OrderService orderService;

    @MockBean
    private PaymentGateway paymentGateway;

    @Test
    void testOrderWithMockedPayment() {
        when(paymentGateway.charge(anyString(), anyDouble()))
            .thenReturn(true);

        Order order = orderService.createOrder(1L, 100.0);

        assertEquals(OrderStatus.COMPLETED, order.getStatus());
        verify(paymentGateway).charge(anyString(), eq(100.0));
    }
}

Best Practices

  • Prefer fakes over mocks — they assert on behavior and survive refactors
  • Reach for the simplest double that works: dummy, then stub, then spy, then fake, and mock only when interaction is the actual behavior under test
  • Double at boundaries — external APIs, databases, file systems — never your own domain logic
  • Reset spies and mocks between tests so state doesn’t leak
  • Use spec= in Python and typed jest.fn() — a double that accepts calls the real object can’t is a test that lies
  • For component and hook tests in React, see Vitest for React: Component, Hook, and Integration Testing

Common Mistakes

  • Over-mocking: doubling everything tests the mocks, not the code — and the suite collapses on the next refactor
  • Doubling what you don’t own: your mock won’t notice when the real API changes; use contract tests at external boundaries
  • Leaked state: mocks and spies keep recorded calls between tests unless you reset them in beforeEach/setup
  • Exact-argument verification: verify(mock).method(arg1, arg2, arg3) breaks on harmless changes — use matchers and verify only what the contract requires
  • A mock where a stub would do: if all you need is a return value, a mock adds expectation machinery nobody asked for

Frequently Asked Questions

What is the difference between a mock and a stub?

A stub returns canned responses — you control what it returns and assert on the result. A mock carries expectations — you verify it received specific calls. Stubs feed input, mocks check output.

What is a fake?

A working implementation with shortcuts — an in-memory repository instead of PostgreSQL. It behaves like the real thing closely enough for unit tests, which is why it usually beats a mock for database-adjacent code.

When should I use a spy vs a mock?

A spy records calls so you can verify them afterward; a mock declares expected calls up front. Spies bend around odd call order, mocks enforce it.

Should I mock the database or use a real one?

Mocking the database tests your mock, not your queries. Reach for a fake in unit tests and a real throwaway database — SQLite, a container, testcontainers — in integration tests.

What is a dummy object?

A placeholder passed to satisfy a signature and never actually called — a no-op logger in a test where nothing gets logged.

The companion runnable test-doubles project has all five types implemented and green in pytest and jest.