Skip to lesson

Why mock: slow, external or unfinished dependencies

ShopLite's OrderService charges a card, saves to MySQL and sends an email. Run its test for real and it takes money and mails customers. How do you test the rules without the outside world?

An OrderService with four dependencies

A dependency is another object a class needs to do its job. OrderService depends on a ProductRepository, an OrderRepository, a PaymentGateway and an EmailSender.

Placing an order needs four helpers. Each one is an interface, so any class that implements it can be passed in.

ProductRepository.javaJava
public interface ProductRepository {      // MySQL in a real app    Optional<Product> findById(int id);    void updateStock(int productId, int newStock);}public interface OrderRepository {        // MySQL in a real app    Order save(Order order);               // returns the order with its new id    List<Order> findByCustomer(int customerId);}public interface PaymentGateway {         // a bank or UPI provider, over the internet    String charge(int customerId, BigDecimal amount);   // payment id, or PaymentDeclinedException}public interface EmailSender {            // a mail server    void sendOrderConfirmation(int customerId, int orderId, BigDecimal total);}

Example 1 · src/main/java/com/shoplite/lab/OrderService.java

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

OrderService.javaJava
package com.shoplite.lab;
import java.math.BigDecimal;
/** Places one order: check the product, take payment, reduce stock, save, send an email. */public class OrderService {
    private static final System.Logger log = System.getLogger(OrderService.class.getName());
    private final ProductRepository products;    private final OrderRepository orders;    private final PaymentGateway payments;    private final EmailSender emails;
    public OrderService(ProductRepository products, OrderRepository orders,                        PaymentGateway payments, EmailSender emails) {        this.products = products;        this.orders = orders;        this.payments = payments;        this.emails = emails;    }
    public 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);   // throws PaymentDeclinedException        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) {            // the customer has paid: a failed email must not undo the order            log.log(System.Logger.Level.WARNING, "Order " + saved.id() + " placed, email failed: " + e.getMessage());        }        return saved;    }}
Files in the mockito-lab project
mockito-lab/
  pom.xml
  src/main/java/com/shoplite/lab/
    Product.java                    record: id, name, price, stock
    Order.java                      record: id, customerId, productId, quantity, total, paymentId
    ProductRepository.java          interface (MySQL in a real app)
    OrderRepository.java            interface (MySQL in a real app)
    PaymentGateway.java             interface (a UPI or card provider)
    EmailSender.java                interface (a mail server)
    ProductNotFoundException.java
    OutOfStockException.java
    PaymentDeclinedException.java
    OrderService.java
  src/test/java/com/shoplite/lab/
    (the tests of the next lessons)

What this code does

  • placeOrder works in a fixed order: find the product, check the stock, charge the customer, reduce the stock, save the order, then send the email.
  • All four dependencies arrive through the constructor; the class never creates them with new. That one choice is what makes it testable.
  • A failed email is caught and logged with System.Logger (built into the JDK). The customer has paid, so a mail problem must not undo the order.

This module uses a cut-down OrderService in a small Maven project, mockito-lab, so each lesson shows only what it needs. The real shoplite-api has no payment gateway yet; here it is a teaching dependency that behaves like a UPI or card provider. The module project then tests the real OrderService.place in shoplite-api.

This lesson starts ShopLite's testing story: the shop works, but every change might break it, so you test OrderService without MySQL, a bank or a mail server.

Slow, external or unfinished dependencies

A unit test checks one class on its own, in milliseconds, with no network or database.

Run a test against the real gateway and the real mail sender, and look at what it does.

Example 2 · Hard-wired dependencies cannot be replaced

HardWiredDemo.javaJava
import java.math.BigDecimal;
class RealPaymentGateway {    String charge(int customerId, BigDecimal amount) {        System.out.println("  [real gateway] calling the bank over the internet...");        System.out.println("  [real gateway] charged Rs " + amount + " to customer " + customerId);        return "pay_live_8841";    }}
class RealEmailSender {    void sendOrderConfirmation(int customerId, int orderId) {        System.out.println("  [real email] sent a mail to customer " + customerId + " about order " + orderId);    }}
class HardWiredOrderService {    // Created inside the class: a test has no way to swap them out    private final RealPaymentGateway payments = new RealPaymentGateway();    private final RealEmailSender emails = new RealEmailSender();    private int nextOrderId = 1001;
    int placeOrder(int customerId, BigDecimal price, int quantity) {        BigDecimal total = price.multiply(BigDecimal.valueOf(quantity));        payments.charge(customerId, total);        int orderId = nextOrderId++;        emails.sendOrderConfirmation(customerId, orderId);        return orderId;    }}
public class HardWiredDemo {    public static void main(String[] args) {        System.out.println("Test: place an order for 2 x Clean Code");        HardWiredOrderService service = new HardWiredOrderService();
        int orderId = service.placeOrder(1, new BigDecimal("499.00"), 2);
        System.out.println("Order id: " + orderId);        System.out.println("The test passed, but it took real money and sent a real mail.");    }}
Output
Test: place an order for 2 x Clean Code
  [real gateway] calling the bank over the internet...
  [real gateway] charged Rs 998.00 to customer 1
  [real email] sent a mail to customer 1 about order 1001
Order id: 1001
The test passed, but it took real money and sent a real mail.

What this code does

  • Both fields are created with new inside HardWiredOrderService, so every caller, including a test, gets the real gateway and the real mail sender.
  • The "test" passed, yet it charged Rs 998.00 and mailed a customer. With a real bank it would also fail whenever the network is down.
  • The fix is not a cleverer test. The class itself must take its dependencies from outside.

A real dependency often makes a unit test impossible. It may be slow: a database or network call takes milliseconds to seconds, and 500 tests must still finish in a few seconds. It may be external: the payment gateway takes real money and the mail server mails real customers. It may be unfinished: a teammate is still writing the EmailSender.

Real dependencies are also not repeatable. The bank may be down today, or a product's stock may have changed since yesterday. Then the same test passes one day and fails the next, with no change in your code. The root cause is the class itself: HardWiredOrderService creates its gateway and mail sender with new, so a test cannot swap them out and running it charges a card.

Find the bug

Find the line that cannot be replaced

Select the line that is wrong.

Which line makes the payment gateway impossible to replace in a test?

Round 1 of 3
If a class creates its own dependencies with new, no test can replace them. Fix the class first, then write the test.

Test doubles and constructor injection

A test double is an object that stands in for a real dependency during a test. It implements the same interface, so the class under test cannot tell the difference.

Pass the stand-ins through the constructor. Here two lambdas replace the bank and the mail server.

The same OrderService in two settings. In the app it uses real dependencies: MySQL tables, a bank over the internet and a mail server. In a test it uses test doubles with the same interfaces: a fake with rows in a HashMap, a stub that always returns pay_501 and a recorder that remembers calls.

Example 3 · Constructor injection with two lambda doubles

InjectedDoublesDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;
interface PaymentGateway {    String charge(int customerId, BigDecimal amount);}
interface EmailSender {    void sendOrderConfirmation(int customerId, int orderId);}
class OrderService {    private final PaymentGateway payments;    private final EmailSender emails;    private int nextOrderId = 1001;
    // The dependencies come in from outside: constructor injection    OrderService(PaymentGateway payments, EmailSender emails) {        this.payments = payments;        this.emails = emails;    }
    int placeOrder(int customerId, BigDecimal price, int quantity) {        BigDecimal total = price.multiply(BigDecimal.valueOf(quantity));        payments.charge(customerId, total);        int orderId = nextOrderId++;        emails.sendOrderConfirmation(customerId, orderId);        return orderId;    }}
public class InjectedDoublesDemo {    public static void main(String[] args) {        List<String> charged = new ArrayList<>();        List<String> mails = new ArrayList<>();
        // Test doubles: tiny stand-ins written as lambdas        PaymentGateway fakeBank = (customerId, amount) -> {            charged.add("customer " + customerId + ": Rs " + amount);            return "pay_test_1";        };        EmailSender fakeMail = (customerId, orderId) -> mails.add("customer " + customerId + ", order " + orderId);
        OrderService service = new OrderService(fakeBank, fakeMail);        int orderId = service.placeOrder(1, new BigDecimal("499.00"), 2);
        System.out.println("Order id: " + orderId);        System.out.println("Charged:  " + charged);        System.out.println("Mails:    " + mails);        System.out.println("No bank, no mail server, no waiting.");    }}
Output
Order id: 1001
Charged:  [customer 1: Rs 998.00]
Mails:    [customer 1, order 1001]
No bank, no mail server, no waiting.

What this code does

  • OrderService now takes a PaymentGateway and an EmailSender in its constructor and cannot tell whether they are real.
  • fakeBank and fakeMail are lambdas. Each adds a line to a list, and the bank one returns a made-up payment id.
  • After the call, the test reads the lists to see what the service did: Rs 998.00 charged to customer 1 and one mail for order 1001.

Constructor injection means a class receives its dependencies as constructor parameters instead of creating them. The app passes the real objects; a test passes doubles. ShopLite's services already work this way, because Spring builds them through their constructors.

When an interface has only one method, a lambda is enough for a quick double. The example passes two lambdas that write down what happened in plain lists.

Predict the output

A lambda as a test double

Read the code and pick what it prints.

What does this program print?

List<String> mails = new ArrayList<>();
EmailSender sender = (customerId, orderId) -> mails.add(customerId + ":" + orderId);
sender.sendOrderConfirmation(1, 1001);
sender.sendOrderConfirmation(2, 1002);
System.out.println(mails);

A hand-written fake, stub and recorder

A fake is a working but simpler version of a dependency, such as a repository that keeps rows in a HashMap instead of MySQL.

Test the whole placeOrder with three hand-written doubles and no library.

Example 4 · Testing placeOrder with hand-written doubles

HandWrittenFakesDemo.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;    }}
// ---------- hand-written test doubles ----------
class InMemoryProductRepository implements ProductRepository {    private final Map<Integer, Product> rows = new HashMap<>();
    void add(Product p) {        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));    }}
class InMemoryOrderRepository implements OrderRepository {    private final List<Order> rows = new ArrayList<>();    private int nextId = 17;
    public Order save(Order order) {        Order saved = order.withId(nextId++);        rows.add(saved);        return saved;    }
    public List<Order> findByCustomer(int customerId) {        return rows.stream().filter(o -> o.customerId() == customerId).toList();    }}
class StubPaymentGateway implements PaymentGateway {    final List<BigDecimal> charges = new ArrayList<>();
    public String charge(int customerId, BigDecimal amount) {        charges.add(amount);        return "pay_501";    }}
class RecordingEmailSender implements EmailSender {    final List<String> sent = new ArrayList<>();
    public void sendOrderConfirmation(int customerId, int orderId, BigDecimal total) {        sent.add("customer " + customerId + ", order " + orderId + ", Rs " + total);    }}
// ---------- the tests ----------
public class HandWrittenFakesDemo {    static int passed = 0;    static int failed = 0;
    static void check(String what, Object expected, Object actual) {        if (Objects.equals(expected, actual)) {            passed++;            System.out.println("  PASS " + what);        } else {            failed++;            System.out.println("  FAIL " + what + ": expected " + expected + " but was " + actual);        }    }
    public static void main(String[] args) {        System.out.println("placeOrder_happyPath");        InMemoryProductRepository products = new InMemoryProductRepository();        products.add(new Product(9, "Clean Code", new BigDecimal("499.00"), 30));        InMemoryOrderRepository orders = new InMemoryOrderRepository();        StubPaymentGateway payments = new StubPaymentGateway();        RecordingEmailSender emails = new RecordingEmailSender();        OrderService service = new OrderService(products, orders, payments, emails);
        Order order = service.placeOrder(1, 9, 2);
        check("order id", 17, order.id());        check("total", new BigDecimal("998.00"), order.total());        check("stock left", 28, products.findById(9).get().stock());        check("amount charged", List.of(new BigDecimal("998.00")), payments.charges);        check("mail sent", List.of("customer 1, order 17, Rs 998.00"), emails.sent);
        System.out.println("placeOrder_unknownProduct");        StubPaymentGateway payments2 = new StubPaymentGateway();        OrderService service2 = new OrderService(new InMemoryProductRepository(),                new InMemoryOrderRepository(), payments2, new RecordingEmailSender());        try {            service2.placeOrder(1, 99, 1);            check("exception thrown", true, false);        } catch (ProductNotFoundException e) {            check("message", "Product 99 does not exist.", e.getMessage());        }        check("nothing charged", 0, payments2.charges.size());
        System.out.println(passed + " checks passed, " + failed + " failed");    }}
Output
placeOrder_happyPath
  PASS order id
  PASS total
  PASS stock left
  PASS amount charged
  PASS mail sent
placeOrder_unknownProduct
  PASS message
  PASS nothing charged
7 checks passed, 0 failed

What this code does

  • InMemoryProductRepository and InMemoryOrderRepository are fakes: they really store data, and the order fake hands out ids from 17 like an auto-increment column.
  • StubPaymentGateway always approves and remembers each amount; RecordingEmailSender remembers each mail. The test checks results (id, total, stock left) and calls (amount charged, mail sent).
  • The unknown-product test checks the message and that nothing was charged: the service stopped before the payment step.

A stub gives fixed answers, such as a gateway that always approves. A recording double remembers each call, so the test can check later what the service did.

The cost shows too: about 50 lines of doubles for one service, and every new interface method means editing them. Mockito, in the next lesson, creates such doubles in one line each.

"Mocks vs stubs vs fakes", later in this module, gives each kind of double its exact name.

Next step

Check your understanding

12 quick questions