Skip to lesson

Mocks vs stubs vs fakes

"Just mock it," says one teammate. "Use a fake," says another. They are not the same thing, and the wrong choice makes tests slow to write or easy to break. Each ShopLite dependency needs the right double.

Dummy, stub, spy, mock and fake

Test double kinds are the five jobs a stand-in can do: a dummy fills a parameter, a stub gives fixed answers, a spy records a real object, a mock is checked for expected calls and a fake is a simpler working version.

One program uses all five doubles around the same OrderService: the happy path and the out-of-stock path.

Example 1 · All five doubles in one program

FiveDoublesDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;
// ---------- the code under test (a cut-down OrderService) ----------
record Product(int id, String name, BigDecimal price, int stock) {}
record Order(Integer id, int customerId, int productId, int quantity, BigDecimal total, String paymentId) {    Order withId(int newId) {        return new Order(newId, customerId, productId, quantity, total, paymentId);    }}
interface ProductRepository {    Optional<Product> findById(int id);
    void updateStock(int productId, int newStock);}
interface OrderRepository {    Order save(Order order);
    List<Order> findByCustomer(int customerId);}
interface PaymentGateway {    String charge(int customerId, BigDecimal amount);}
interface EmailSender {    void sendOrderConfirmation(int customerId, int orderId, BigDecimal total);}
class ProductNotFoundException extends RuntimeException {    ProductNotFoundException(int productId) {        super("Product " + productId + " does not exist.");    }}
class OutOfStockException extends RuntimeException {    OutOfStockException(String name, int available, int requested) {        super("Only " + available + " units of " + name + " are in stock; " + requested + " were requested.");    }}
class OrderService {    private final ProductRepository products;    private final OrderRepository orders;    private final PaymentGateway payments;    private final EmailSender emails;
    OrderService(ProductRepository products, OrderRepository orders, PaymentGateway payments, EmailSender emails) {        this.products = products;        this.orders = orders;        this.payments = payments;        this.emails = emails;    }
    Order placeOrder(int customerId, int productId, int quantity) {        Product product = products.findById(productId)                .orElseThrow(() -> new ProductNotFoundException(productId));        if (product.stock() < quantity) {            throw new OutOfStockException(product.name(), product.stock(), quantity);        }        BigDecimal total = product.price().multiply(BigDecimal.valueOf(quantity));        String paymentId = payments.charge(customerId, total);        products.updateStock(productId, product.stock() - quantity);        Order saved = orders.save(new Order(null, customerId, productId, quantity, total, paymentId));        try {            emails.sendOrderConfirmation(customerId, saved.id(), total);        } catch (RuntimeException e) {            System.out.println("WARNING: Order " + saved.id() + " placed, email failed: " + e.getMessage());        }        return saved;    }}

// ---------- the five kinds of test double ----------
/** FAKE: a real, simpler implementation (rows in a HashMap instead of MySQL). */class FakeProductRepository implements ProductRepository {    private final Map<Integer, Product> rows = new HashMap<>();
    FakeProductRepository(Product... products) {        for (Product p : products) {            rows.put(p.id(), p);        }    }
    public Optional<Product> findById(int id) {        return Optional.ofNullable(rows.get(id));    }
    public void updateStock(int productId, int newStock) {        Product p = rows.get(productId);        rows.put(productId, new Product(p.id(), p.name(), p.price(), newStock));    }}
/** FAKE as well: saves orders in a list and gives ids from 17. */class FakeOrderRepository implements OrderRepository {    final List<Order> rows = new ArrayList<>();
    public Order save(Order order) {        Order saved = order.withId(17 + rows.size());        rows.add(saved);        return saved;    }
    public List<Order> findByCustomer(int customerId) {        return rows.stream().filter(o -> o.customerId() == customerId).toList();    }}
/** SPY: wraps a real object, passes every call on, and remembers the calls. */class SpyOrderRepository implements OrderRepository {    private final OrderRepository real;    int saveCalls = 0;
    SpyOrderRepository(OrderRepository real) {        this.real = real;    }
    public Order save(Order order) {        saveCalls++;        return real.save(order);    }
    public List<Order> findByCustomer(int customerId) {        return real.findByCustomer(customerId);    }}
/** MOCK: knows which call it expects and can check afterwards that it happened. */class MockEmailSender implements EmailSender {    private final String expected;    private final List<String> received = new ArrayList<>();
    MockEmailSender(int customerId, int orderId, String total) {        this.expected = customerId + "/" + orderId + "/" + total;    }
    public void sendOrderConfirmation(int customerId, int orderId, BigDecimal total) {        received.add(customerId + "/" + orderId + "/" + total);    }
    String verify() {        return received.equals(List.of(expected)) ? "as expected" : "expected " + expected + " but got " + received;    }}
public class FiveDoublesDemo {    static final Product CLEAN_CODE = new Product(9, "Clean Code", new BigDecimal("499.00"), 30);
    public static void main(String[] args) {        // STUB: fixed answer, no logic        PaymentGateway stub = (customerId, amount) -> "pay_501";        EmailSender dummy = (customerId, orderId, total) -> {            throw new AssertionError("dummy must not be used");        };
        System.out.println("Out-of-stock test: fake products, stub payment, dummy email");        OrderService s1 = new OrderService(new FakeProductRepository(CLEAN_CODE), new FakeOrderRepository(),                stub, dummy);        try {            s1.placeOrder(1, 9, 31);        } catch (OutOfStockException e) {            System.out.println("  " + e.getMessage());        }
        System.out.println("Happy-path test: fake products, spy orders, stub payment, mock email");        FakeProductRepository products = new FakeProductRepository(CLEAN_CODE);        FakeOrderRepository realOrders = new FakeOrderRepository();        SpyOrderRepository spy = new SpyOrderRepository(realOrders);        MockEmailSender mock = new MockEmailSender(1, 17, "998.00");        OrderService s2 = new OrderService(products, spy, stub, mock);
        s2.placeOrder(1, 9, 2);
        System.out.println("  state (fake):     stock " + products.findById(9).get().stock()                + ", orders of customer 1: " + realOrders.findByCustomer(1).size());        System.out.println("  spy:              save called " + spy.saveCalls + " time(s)");        System.out.println("  behaviour (mock): email " + mock.verify());    }}
Output
Out-of-stock test: fake products, stub payment, dummy email
  Only 30 units of Clean Code are in stock; 31 were requested.
Happy-path test: fake products, spy orders, stub payment, mock email
  state (fake):     stock 28, orders of customer 1: 1
  spy:              save called 1 time(s)
  behaviour (mock): email as expected

What this code does

  • The out-of-stock test uses a dummy email sender that throws if touched: the service stops before the email, so it is never used.
  • In the happy path, the fake keeps real state (stock 28, one order), the spy passes save to the real fake and counts it, and the mock checks it got exactly the email it expected.
  • The stub gateway always says pay_501; it has no logic and no checks, it only feeds an answer into the service.

The five names come from Gerard Meszaros's book xUnit Test Patterns and are used across languages.

  • A dummy only fills a parameter and is never used, like an EmailSender in a test that stops before any email.
  • A stub gives fixed answers to calls, such as a gateway that always returns pay_501.
  • A spy wraps or records a real object: calls really run, and the test can check them later.
  • A mock is set up with expected calls and checked afterwards: "one email to customer 1 for order 17".
  • A fake is a working, simpler implementation, such as a repository backed by a HashMap.

Mockito's mock() can act as a dummy, a stub or a mock, depending on whether you stub it, verify it or neither. spy() makes a spy. Fakes you write yourself.

Predict the output

Which kind of double is it?

Read the code and pick what it prints.

Round 1 of 4

Which kind of double is sender?

EmailSender sender = mock(EmailSender.class);
service.placeOrder(1, 9, 2);
verify(sender).sendOrderConfirmation(1, 17, new BigDecimal("998.00"));

An in-memory fake repository vs a mocked repository

A fake is a working, simpler implementation of a dependency, such as a repository backed by a HashMap. It stores data for real, so a test can read the result back.

A fake repository stores data for real, so the test reads the result back. A mocked repository stores nothing; the test stubs answers and verifies calls.

Example 2 · Two fakes shared by many tests

Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)

Java
// src/test/java/com/shoplite/lab/InMemoryProductRepository.javapackage com.shoplite.lab;
import java.util.HashMap;import java.util.Map;import java.util.Optional;
/** A fake for tests: products in a HashMap instead of MySQL. */class InMemoryProductRepository implements ProductRepository {
    private final Map<Integer, Product> rows = new HashMap<>();
    InMemoryProductRepository(Product... products) {        for (Product p : products) {            rows.put(p.id(), p);        }    }
    @Override    public Optional<Product> findById(int id) {        return Optional.ofNullable(rows.get(id));    }
    @Override    public void updateStock(int productId, int newStock) {        Product p = rows.get(productId);        rows.put(productId, new Product(p.id(), p.name(), p.price(), newStock));    }}
// src/test/java/com/shoplite/lab/InMemoryOrderRepository.javaimport java.util.ArrayList;import java.util.List;
/** A fake for tests: orders in a list, ids from 17 like an auto-increment column. */class InMemoryOrderRepository implements OrderRepository {
    private final List<Order> rows = new ArrayList<>();
    @Override    public Order save(Order order) {        Order saved = order.withId(17 + rows.size());        rows.add(saved);        return saved;    }
    @Override    public List<Order> findByCustomer(int customerId) {        return rows.stream().filter(o -> o.customerId() == customerId).toList();    }}
Where they live
src/test/java/com/shoplite/lab/
  InMemoryProductRepository.java     fake, used by many test classes
  InMemoryOrderRepository.java       fake, used by many test classes
  OrderServiceWithFakesTest.java     next example

What this code does

  • Fakes live in src/test/java, so they are never packaged with the app. They implement the same interfaces as the MySQL versions.
  • InMemoryOrderRepository hands out ids from 17 like an auto-increment column, so tests can check the id an order really got.

Example 3 · src/test/java/com/shoplite/lab/OrderServiceWithFakesTest.java

Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)

Java
package com.shoplite.lab;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;
/** Fakes for the two repositories (our own types, simple data), mocks for the two outside services. */@ExtendWith(MockitoExtension.class)class OrderServiceWithFakesTest {
    InMemoryProductRepository products;    InMemoryOrderRepository orders;    @Mock    PaymentGateway payments;    @Mock    EmailSender emails;
    OrderService service;
    @BeforeEach    void setUp() {        products = new InMemoryProductRepository(                new Product(9, "Clean Code", new BigDecimal("499.00"), 30),                new Product(3, "iPhone 15 128GB", new BigDecimal("69900.00"), 8));        orders = new InMemoryOrderRepository();        service = new OrderService(products, orders, payments, emails);    }
    @Test    void placeOrder_storesTheOrderAndReducesStock() {        when(payments.charge(eq(1), any(BigDecimal.class))).thenReturn("pay_501");
        service.placeOrder(1, 9, 2);
        assertEquals(28, products.findById(9).orElseThrow().stock());            // state        Order stored = orders.findByCustomer(1).get(0);        assertEquals(new BigDecimal("998.00"), stored.total());        assertEquals("pay_501", stored.paymentId());        verify(emails).sendOrderConfirmation(1, 17, new BigDecimal("998.00"));   // behaviour    }
    @Test    void placeOrder_outOfStock_changesNothing() {        assertThrows(OutOfStockException.class, () -> service.placeOrder(2, 3, 9));
        assertEquals(8, products.findById(3).orElseThrow().stock());        assertTrue(orders.findByCustomer(2).isEmpty());    }}
Sample output
[INFO] Running com.shoplite.lab.OrderServiceWithFakesTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.873 s -- in com.shoplite.lab.OrderServiceWithFakesTest

What this code does

  • Repositories are fakes, so the test reads the stock (28) and the stored order back: state verification, with no stubbing of findById or save.
  • The gateway and email sender are mocks: one stubbing for the payment id and one verify for the email, the only effect that leaves no readable state.
  • The out-of-stock test needs no Mockito at all: the fake still holds 8 units and customer 2 has no orders.

Fakes shine for your own simple data types, such as repositories. They are written once in src/test/java and shared by many tests. Those tests check results, so they survive changes in how the service talks to the repository.

Mocks shine for outside services and for failures that are hard to fake: a declined card, a server that is down. The usual mix in a service test is fakes for repositories and mocks for gateways and senders.

@Spy and partial mocks, and why they are rarely needed

A partial mock is a spy with some methods replaced: doReturn(100).when(names).size() replaces only size() and every other method still runs for real.

A spy wraps a real object, so every call runs for real. This test replaces one method of a real list and meets a trap.

Example 4 · @Spy on a fake, a partial mock and the when-on-a-spy trap

Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)

Java
package com.shoplite.lab;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.spy;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;
import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.Spy;import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)class SpyExamplesTest {
    @Spy    InMemoryOrderRepository orders = new InMemoryOrderRepository();   // real object, calls recorded    @Spy    InMemoryProductRepository products =            new InMemoryProductRepository(new Product(9, "Clean Code", new BigDecimal("499.00"), 30));    @Mock    PaymentGateway payments;    @Mock    EmailSender emails;
    @InjectMocks    OrderService service;
    @Test    void spyOnAFake_realSaveAndVerify() {        when(payments.charge(eq(1), any(BigDecimal.class))).thenReturn("pay_501");
        service.placeOrder(1, 9, 2);
        assertEquals(1, orders.findByCustomer(1).size());   // the real save ran        verify(orders).save(any(Order.class));               // and the call was recorded    }
    @Test    void partialMock_doReturnOverridesOneMethod() {        List<String> names = spy(new ArrayList<String>());        names.add("Asha");        doReturn(100).when(names).size();
        assertEquals(100, names.size());        assertEquals("Asha", names.get(0));    }
    @Test    void whenOnASpy_callsTheRealMethod() {        List<String> names = spy(new ArrayList<String>());        when(names.get(0)).thenReturn("Ravi");    }}
Sample output
[INFO] Running com.shoplite.lab.SpyExamplesTest
[ERROR] Tests run: 3, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.032 s <<< FAILURE! -- in com.shoplite.lab.SpyExamplesTest
[ERROR] com.shoplite.lab.SpyExamplesTest.whenOnASpy_callsTheRealMethod -- Time elapsed: 0.003 s <<< ERROR!
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
	...
	at java.base/java.util.ArrayList.get(ArrayList.java:427)
	at com.shoplite.lab.SpyExamplesTest.whenOnASpy_callsTheRealMethod(SpyExamplesTest.java:61)

What this code does

  • @Spy fields are real objects that Mockito records; @InjectMocks passes spies and mocks to the constructor alike. The first test checks real state and a recorded save.
  • doReturn(100).when(names).size() replaces one method of a real ArrayList; get(0) still runs for real and returns "Asha".
  • when(names.get(0)) runs the real get(0) on an empty list first, so the test dies with IndexOutOfBoundsException before anything is stubbed.

The trap: when(spy.get(0)) really calls get(0) while you stub it, so on an empty list it throws IndexOutOfBoundsException before stubbing happens. For spies, always use the do-family: doReturn(x).when(spy).method().

Needing a partial mock usually means a class does too much: you want to keep half of it real and replace the other half. Split the class and inject the part you want to replace instead. Spies stay useful for checking calls on a fake or on legacy code you cannot change yet.

Fix the error

Stub a spy safely

Read the error, then pick the line that fixes it.

This stubbing on a spy fails before it stubs anything. Replace line 2.

List<String> carts = spy(new ArrayList<String>());
when(carts.get(2)).thenReturn("Pen");

Error

java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 0

State verification vs behaviour verification

State vs behaviour verification are two ways to check a result. State verification checks data after the call; behaviour verification checks the calls a mock received, such as verify(mock).updateStock(9, 28).

The same test written two ways: first it looks at data, then it looks at calls.

Java
// State: run, then look at the data (fake repositories)service.placeOrder(1, 9, 2);assertEquals(28, products.findById(9).orElseThrow().stock());assertEquals(1, orders.findByCustomer(1).size());
// Behaviour: run, then look at the calls (mocked repositories)service.placeOrder(1, 9, 2);verify(productsMock).updateStock(9, 28);verify(ordersMock).save(any(Order.class));

State checks say what happened, so they survive a refactor that changes how it happened. Behaviour checks are right when the call is the result: an email sent, a payment charged, nothing saved on an error path.

A good default: check state where you can, and verify calls only for effects that leave no state you can read.

Choosing the simplest double that works

Start from the question the test asks, and pick the smallest double that answers it.

  • Parameter not used on this path → a dummy (Mockito mock() with no stubbing is fine).
  • The code needs an answer or a failure → a stub (when(...).thenReturn / thenThrow).
  • The test needs data that changes, read back later → a fake (in-memory repository).
  • The call itself is the result (email, payment, nothing saved) → a mock with verify.
Choosing a test double by the question the test asks. Parameter not used on this path: dummy. Needs an answer or a failure: stub. Needs data to store and read back: fake. The call itself is the result: mock with verify. Wrap a real object and record calls: spy. A record or value needs no double.
A real object is the simplest double of all. Records, value objects and small pure classes such as a price calculator should simply be used for real.

Next step

Check your understanding

12 quick questions