QA and Test Automation · Lab 6 of 35

Unit Tests With Mocks, Stubs and Fakes: JUnit 5 and Mockito Lab

Unit-test ShopRung's checkout logic without a payment provider, a database or the real date: a Mockito mock (or unittest.mock) for payments, an in-memory fake for orders, and a fixed clock for the coupon expiry. Six fast tests for approved, declined and failing payments.

⏱ 60 minIntermediate💸 Free7 stepsJava + Python

Java 21 + MavenJUnit 5.11Mockito 5.14Python 3.12 + pytest + unittest.mock (second path)

Overview video

1 / 6

0 of 7 steps done

What you will build

A small checkout module and 6 unit tests that run in milliseconds, with no network, database or real clock:

  • CheckoutService prices a cart with the rules from lab 4, charges a payment gateway, and saves the order to an order repository. All three dependencies are passed in.
  • Tests replace them with test doubles: a Mockito mock that answers "approved", "declined" or throws; an in-memory fake repository; and a fixed clock.
  • The tests prove the rules that matter at checkout: the discounted total is charged ($49.99 for $50.00 with SAVE10), a declined or failing payment saves nothing, an empty cart or an unknown coupon never reaches the provider, and WELCOME15 works on 31 December 2025 but not on 1 January 2026.

Before you start

Setup

S1Java 21 and Maven, or Python 3.12

From lab 4. Check the versions for the path you take.

Run
java -version
mvn -v
# or
python3 --version

S2Make the project

Java: the Maven folders for code and tests. Python: a package folder shop, a tests folder and a virtual environment.

Run
# Java
mkdir -p shoprung-checkout/src/main/java/dev/algorung/shop shoprung-checkout/src/test/java/dev/algorung/shop
# Python
mkdir -p shoprung-checkout-py/shop shoprung-checkout-py/tests && cd shoprung-checkout-py && python3 -m venv .venv && source .venv/bin/activate
1

The project and the pricing rules

A build file with JUnit and Mockito, and the money rules from lab 4.

Create pom.xml. It adds Mockito, the most used Java library for test doubles, with its JUnit 5 integration. Then copy Pricing.java and Coupon.java from lab 4 (shown again in full here): checkout uses them to price the cart.

Python: unittest.mock is part of the standard library, so requirements.txt only needs pytest. Copy pricing.py from lab 4 into the shop package.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>dev.algorung</groupId>
  <artifactId>shoprung-checkout</artifactId>
  <version>0.1.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>5.11.4</junit.version>
    <mockito.version>5.14.2</mockito.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-junit-jupiter</artifactId>
      <version>${mockito.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.13.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.2</version>
      </plugin>
    </plugins>
  </build>
</project>
  1. Mockito plus MockitoExtension for JUnit 5. It brings mockito-core.line 26
src/main/java/dev/algorung/shop/Pricing.java
package dev.algorung.shop;

import java.time.LocalDate;

/**
 * ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Java.
 * Every amount is whole cents in a long: $50.00 is 5000. No double, so no rounding surprises.
 */
public final class Pricing {
    public static final long FREE_SHIPPING_FROM = 7_500; // $75.00, after the discount
    public static final long SHIPPING = 499;             // $4.99

    /** The four numbers a cart shows. */
    public record Totals(long subtotal, long discount, long shipping, long total) {}

    private Pricing() {}

    /** 1250 becomes "$12.50" (PRICE-1). */
    public static String money(long cents) {
        if (cents < 0) throw new IllegalArgumentException("cents must not be negative: " + cents);
        return String.format("$%d.%02d", cents / 100, cents % 100);
    }

    /** $4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing. */
    public static long shipping(long afterDiscount) {
        if (afterDiscount == 0) return 0;
        return afterDiscount >= FREE_SHIPPING_FROM ? 0 : SHIPPING;
    }

    /** Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8). */
    public static Totals totals(long subtotal, Coupon coupon, LocalDate today) {
        if (subtotal < 0) throw new IllegalArgumentException("subtotal must not be negative: " + subtotal);
        long discount = 0;
        if (coupon != null && coupon.problem(subtotal, today) == null) discount = coupon.discount(subtotal);
        long shipping = shipping(subtotal - discount);
        return new Totals(subtotal, discount, shipping, subtotal - discount + shipping);
    }
}
  1. From lab 4: subtotal, discount, shipping, total, all in cents.line 31
src/main/java/dev/algorung/shop/Coupon.java
package dev.algorung.shop;

import java.time.LocalDate;
import java.util.Locale;

/** ShopRung's three coupons (PRICE-2 to PRICE-7), with the same rules and messages as the shop. */
public enum Coupon {
    SAVE10(true, 10, 5_000, null),                       // 10% off from $50.00
    FLAT5(false, 500, 2_000, null),                      // $5.00 off from $20.00
    WELCOME15(true, 15, 0, LocalDate.of(2025, 12, 31));  // expired

    private final boolean percent;
    private final long amount;      // a percent, or cents
    private final long minSubtotal; // cents
    private final LocalDate expiresOn;

    Coupon(boolean percent, long amount, long minSubtotal, LocalDate expiresOn) {
        this.percent = percent;
        this.amount = amount;
        this.minSubtotal = minSubtotal;
        this.expiresOn = expiresOn;
    }

    /** Finds a coupon by code. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7). */
    public static Coupon of(String code) {
        String c = code == null ? "" : code.trim().toUpperCase(Locale.ROOT);
        for (Coupon coupon : values()) {
            if (coupon.name().equals(c)) return coupon;
        }
        throw new IllegalArgumentException("No coupon called " + (c.isEmpty() ? "(empty)" : c));
    }

    /** Why this coupon cannot be used, or null when it can. */
    public String problem(long subtotal, LocalDate today) {
        if (expiresOn != null && today.isAfter(expiresOn)) return "This coupon has expired";
        if (subtotal < minSubtotal) return "This coupon needs a subtotal of at least " + Pricing.money(minSubtotal);
        return null;
    }

    /** The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6). */
    public long discount(long subtotal) {
        if (percent) return (subtotal * amount + 50) / 100;
        return Math.min(amount, subtotal); // a fixed amount never makes the total negative
    }
}
  1. Expires on 31 December 2025: the clock decides whether it applies.line 10
2

The code under test, and its dependencies

A CheckoutService that receives its payment gateway, order store and clock from outside.

Checkout has three dependencies that make testing hard: a payment provider (a paid web service you cannot make decline on demand), an order store (a database), and today's date (which changes, and decides whether WELCOME15 applies).

The design choice that makes unit testing possible: CheckoutService does not create these itself. It receives them in its constructor, as interfaces (PaymentGateway, OrderRepository) and a Clock. This is called dependency injection. In production you pass the real ones; in tests, doubles.

Read checkout carefully: price the cart, charge the card, and only if the payment is approved, save the order. That order of steps is the rule your tests will protect.

src/main/java/dev/algorung/shop/PaymentGateway.java
package dev.algorung.shop;

/** The card payment provider. The real one is a paid web service; tests replace it. */
public interface PaymentGateway {
    /** The answer from the provider: approved, or declined with a reason. */
    record Result(boolean approved, String reason) {
        public static Result ok() { return new Result(true, null); }
        public static Result declined(String reason) { return new Result(false, reason); }
    }

    Result charge(String orderRef, long amountCents);
}
  1. One method: easy to replace in tests.line 11
src/main/java/dev/algorung/shop/Order.java
package dev.algorung.shop;

/** A placed and paid order. */
public record Order(String ref, String customer, long totalCents, String coupon) {}
src/main/java/dev/algorung/shop/OrderRepository.java
package dev.algorung.shop;

import java.util.List;

/** Where orders are stored. The real one is a database. */
public interface OrderRepository {
    void save(Order order);

    List<Order> findAll();
}
src/main/java/dev/algorung/shop/PaymentDeclinedException.java
package dev.algorung.shop;

/** Thrown when the provider says no. Nothing is saved. */
public class PaymentDeclinedException extends RuntimeException {
    public PaymentDeclinedException(String reason) {
        super("Payment declined: " + reason);
    }
}
src/main/java/dev/algorung/shop/CheckoutService.java
package dev.algorung.shop;

import java.time.Clock;
import java.time.LocalDate;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Checkout: price the cart, charge the card, save the order. The three things it depends on (the payment
 * provider, the order store and the clock) are passed in, so a test can replace each one.
 */
public class CheckoutService {
    private final PaymentGateway payments;
    private final OrderRepository orders;
    private final Clock clock;
    private final AtomicInteger next = new AtomicInteger(1);

    public CheckoutService(PaymentGateway payments, OrderRepository orders, Clock clock) {
        this.payments = payments;
        this.orders = orders;
        this.clock = clock;
    }

    /** Charges the discounted total and saves the order. A declined payment saves nothing. */
    public Order checkout(String customer, long subtotalCents, String couponCode) {
        if (subtotalCents <= 0) throw new IllegalArgumentException("Your cart is empty");
        Coupon coupon = couponCode == null ? null : Coupon.of(couponCode);
        LocalDate today = LocalDate.now(clock);
        Pricing.Totals totals = Pricing.totals(subtotalCents, coupon, today);

        String ref = "ORD-" + next.getAndIncrement();
        PaymentGateway.Result result = payments.charge(ref, totals.total());
        if (!result.approved()) throw new PaymentDeclinedException(result.reason());

        boolean applied = totals.discount() > 0;
        Order order = new Order(ref, customer, totals.total(), applied ? coupon.name() : null);
        orders.save(order);
        return order;
    }
}
  1. Dependencies come in from outside: that is what makes this testable.line 17
  2. Never LocalDate.now(): the clock is injected.line 27
  3. Declined: stop before saving anything.line 32
  4. Saved only after an approved payment.line 36
3

Test doubles: a fake, a mock and a fixed clock

Three different doubles, each the right tool for its dependency.

Each dependency gets the double that suits it:

  • Order store → a fake. InMemoryOrderRepository is a real, working implementation that keeps orders in a list. Tests check its contents afterwards: "was an order saved?" A fake is best when the dependency has simple behaviour you can rebuild.
  • Payment provider → a mock. Mockito (or create_autospec in Python) creates an object with the same methods, whose answers the test stubs ("return approved") and whose calls the test verifies ("was it charged 4999 cents?").
  • Today → a fixed clock. Clock.fixed(...) always says 30 November 2026. In Python, today is a lambda that returns a fixed date.

Python keeps all three in tests/conftest.py as fixtures. create_autospec(PaymentGateway, instance=True) matters: calling charge with the wrong arguments raises an error, instead of silently passing like a plain Mock would.

src/test/java/dev/algorung/shop/InMemoryOrderRepository.java
package dev.algorung.shop;

import java.util.ArrayList;
import java.util.List;

/** A fake: a real, working OrderRepository that keeps orders in a list instead of a database. */
class InMemoryOrderRepository implements OrderRepository {
    private final List<Order> saved = new ArrayList<>();

    @Override
    public void save(Order order) {
        saved.add(order);
    }

    @Override
    public List<Order> findAll() {
        return List.copyOf(saved);
    }
}
  1. A real implementation, just without a database.line 7
4

The first test: stub, act, verify

SAVE10 at $50.00 charges exactly 4999 cents and saves one order.

Create the test class. In Java, @ExtendWith(MockitoExtension.class) creates the @Mock fields before each test. @BeforeEach builds a fresh fake and a fresh CheckoutService, so tests never share state.

The test has three parts. Arrange: stub the gateway to approve any charge. Act: check out $50.00 with save10. Assert: verify the gateway was charged "ORD-1" and 4999 cents ($50.00 - $5.00 + $4.99 shipping), and that the order was saved with the coupon. Verifying the call is the point of a mock: it proves your code sent the right amount to a service you cannot see.

src/test/java/dev/algorung/shop/CheckoutServiceTest.java
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
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;

@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
    // A stub/mock for the paid payment provider: we decide its answers and check how it was called.
    @Mock PaymentGateway payments;
    // A fake: a real, simple implementation of the order store.
    InMemoryOrderRepository orders;
    // A fixed clock: "today" is always 30 November 2026 in these tests.
    Clock clock = Clock.fixed(Instant.parse("2026-11-30T10:00:00Z"), ZoneOffset.UTC);
    CheckoutService checkout;

    @BeforeEach
    void setUp() {
        orders = new InMemoryOrderRepository();
        checkout = new CheckoutService(payments, orders, clock);
    }

    @Test
    void chargesTheDiscountedTotalAndSavesTheOrder() {
        when(payments.charge(anyString(), anyLong())).thenReturn(PaymentGateway.Result.ok());

        Order order = checkout.checkout("alice@shoprung.test", 5_000, "save10");

        verify(payments).charge("ORD-1", 4_999);  // $50.00 - $5.00 + $4.99 shipping
        assertEquals(4_999, order.totalCents());
        assertEquals("SAVE10", order.coupon());
        assertEquals(1, orders.findAll().size());
    }
}
  1. Creates the mocks and checks for unused stubs (strict stubs).line 18
  2. A mock: no real behaviour until you stub it.line 21
  3. Arrange: the stubbed answer.line 36
  4. Assert on the interaction: exactly this call, exactly once.line 40
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Running dev.algorung.shop.CheckoutServiceTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
5

The failure paths

Declined, provider errors, an empty cart and an unknown coupon: four tests, none of which you could do against a real provider.

Replace the test file. The new tests are the reason to mock at all: you cannot make a real card provider decline on demand or time out, but a stub can.

  • Declined: stub declined("card_declined"). Checkout must throw Payment declined: card_declined, and the fake must be empty: no order saved.
  • Provider error: stub the call to throw. The error must reach the caller (not be swallowed), and nothing is saved.
  • Empty cart: checkout refuses, and verifyNoInteractions(payments) (Python: assert_not_called()) proves the provider was never even called.
  • Unknown coupon: No coupon called NOPE, before any charge.
src/test/java/dev/algorung/shop/CheckoutServiceTest.java 25 new or changed lines
package dev.algorung.shop;

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.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
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;

@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
    // A stub/mock for the paid payment provider: we decide its answers and check how it was called.
    @Mock PaymentGateway payments;
    // A fake: a real, simple implementation of the order store.
    InMemoryOrderRepository orders;
    // A fixed clock: "today" is always 30 November 2026 in these tests.
    Clock clock = Clock.fixed(Instant.parse("2026-11-30T10:00:00Z"), ZoneOffset.UTC);
    CheckoutService checkout;

    @BeforeEach
    void setUp() {
        orders = new InMemoryOrderRepository();
        checkout = new CheckoutService(payments, orders, clock);
    }

    @Test
    void chargesTheDiscountedTotalAndSavesTheOrder() {
        when(payments.charge(anyString(), anyLong())).thenReturn(PaymentGateway.Result.ok());

        Order order = checkout.checkout("alice@shoprung.test", 5_000, "save10");

        verify(payments).charge("ORD-1", 4_999);  // $50.00 - $5.00 + $4.99 shipping
        assertEquals(4_999, order.totalCents());
        assertEquals("SAVE10", order.coupon());
        assertEquals(1, orders.findAll().size());
    }

    @Test
    void aDeclinedPaymentSavesNothing() {
        when(payments.charge(anyString(), anyLong())).thenReturn(PaymentGateway.Result.declined("card_declined"));

        PaymentDeclinedException e = assertThrows(PaymentDeclinedException.class,
                () -> checkout.checkout("alice@shoprung.test", 5_000, null));

        assertEquals("Payment declined: card_declined", e.getMessage());
        assertTrue(orders.findAll().isEmpty(), "no order may be saved when payment fails");
    }

    @Test
    void aProviderErrorIsNotSwallowed() {
        when(payments.charge(anyString(), anyLong())).thenThrow(new IllegalStateException("provider timed out"));

        IllegalStateException e = assertThrows(IllegalStateException.class,
                () -> checkout.checkout("alice@shoprung.test", 2_000, null));

        assertEquals("provider timed out", e.getMessage());
        assertTrue(orders.findAll().isEmpty());
    }

    @Test
    void anEmptyCartNeverReachesThePaymentProvider() {
        assertThrows(IllegalArgumentException.class, () -> checkout.checkout("alice@shoprung.test", 0, null));
        verifyNoInteractions(payments);
    }

    @Test
    void anUnknownCouponStopsCheckoutBeforePaying() {
        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
                () -> checkout.checkout("alice@shoprung.test", 5_000, "NOPE"));
        assertEquals("No coupon called NOPE", e.getMessage());
        verify(payments, never()).charge(anyString(), eq(5_000L));
    }
}
  1. The answer a real provider would never give you on cue.line 53
  2. The fake answers "what was saved?": nothing.line 59
  3. Simulate a timeout or outage.line 64
  4. Not one call reached the provider.line 76
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
6

Control time, and capture arguments

WELCOME15 on its last day and the day after, with both charged amounts captured.

WELCOME15 expires on 31 December 2025, and that day still counts. Testing that with the real clock is impossible, so the test builds two services with two fixed clocks: 31 December 2025 and 1 January 2026, and checks out $40.00 with WELCOME15 on each.

An ArgumentCaptor (Python: call_args_list) collects every amount the mock was charged. The expected list is 3899 (15% off $40.00 is $6.00, plus $4.99 shipping) and then 4499 (no discount the day after).

src/test/java/dev/algorung/shop/CheckoutServiceTest.java 11 new or changed lines
package dev.algorung.shop;

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.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
    // A stub/mock for the paid payment provider: we decide its answers and check how it was called.
    @Mock PaymentGateway payments;
    // A fake: a real, simple implementation of the order store.
    InMemoryOrderRepository orders;
    // A fixed clock: "today" is always 30 November 2026 in these tests.
    Clock clock = Clock.fixed(Instant.parse("2026-11-30T10:00:00Z"), ZoneOffset.UTC);
    CheckoutService checkout;

    @BeforeEach
    void setUp() {
        orders = new InMemoryOrderRepository();
        checkout = new CheckoutService(payments, orders, clock);
    }

    @Test
    void chargesTheDiscountedTotalAndSavesTheOrder() {
        when(payments.charge(anyString(), anyLong())).thenReturn(PaymentGateway.Result.ok());

        Order order = checkout.checkout("alice@shoprung.test", 5_000, "save10");

        verify(payments).charge("ORD-1", 4_999);  // $50.00 - $5.00 + $4.99 shipping
        assertEquals(4_999, order.totalCents());
        assertEquals("SAVE10", order.coupon());
        assertEquals(1, orders.findAll().size());
    }

    @Test
    void aDeclinedPaymentSavesNothing() {
        when(payments.charge(anyString(), anyLong())).thenReturn(PaymentGateway.Result.declined("card_declined"));

        PaymentDeclinedException e = assertThrows(PaymentDeclinedException.class,
                () -> checkout.checkout("alice@shoprung.test", 5_000, null));

        assertEquals("Payment declined: card_declined", e.getMessage());
        assertTrue(orders.findAll().isEmpty(), "no order may be saved when payment fails");
    }

    @Test
    void aProviderErrorIsNotSwallowed() {
        when(payments.charge(anyString(), anyLong())).thenThrow(new IllegalStateException("provider timed out"));

        IllegalStateException e = assertThrows(IllegalStateException.class,
                () -> checkout.checkout("alice@shoprung.test", 2_000, null));

        assertEquals("provider timed out", e.getMessage());
        assertTrue(orders.findAll().isEmpty());
    }

    @Test
    void anEmptyCartNeverReachesThePaymentProvider() {
        assertThrows(IllegalArgumentException.class, () -> checkout.checkout("alice@shoprung.test", 0, null));
        verifyNoInteractions(payments);
    }

    @Test
    void welcome15WorksOnItsLastDayAndNotTheDayAfter() {
        when(payments.charge(anyString(), anyLong())).thenReturn(PaymentGateway.Result.ok());
        Clock lastDay = Clock.fixed(Instant.parse("2025-12-31T12:00:00Z"), ZoneOffset.UTC);
        Clock dayAfter = Clock.fixed(Instant.parse("2026-01-01T12:00:00Z"), ZoneOffset.UTC);

        new CheckoutService(payments, orders, lastDay).checkout("alice@shoprung.test", 4_000, "WELCOME15");
        new CheckoutService(payments, orders, dayAfter).checkout("alice@shoprung.test", 4_000, "WELCOME15");

        ArgumentCaptor<Long> amounts = ArgumentCaptor.forClass(Long.class);
        verify(payments, times(2)).charge(anyString(), amounts.capture());
        assertEquals(List.of(3_899L, 4_499L), amounts.getAllValues()); // 15% off, then no discount
    }

    @Test
    void anUnknownCouponStopsCheckoutBeforePaying() {
        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
                () -> checkout.checkout("alice@shoprung.test", 5_000, "NOPE"));
        assertEquals("No coupon called NOPE", e.getMessage());
        verify(payments, never()).charge(anyString(), eq(5_000L));
    }
}
  1. Time becomes a test input like any other.line 85
  2. Collects the arguments of every call.line 91
  3. Both edges of the expiry date in one check.line 93
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
7

When not to mock

Know the limits, so your mocks help instead of hiding bugs.

These tests prove your checkout logic, fast. They do not prove the real payment provider accepts your requests: a mock answers whatever you tell it. That is what API, contract and end-to-end tests are for (contract testing).

Rules of thumb teams use:

  • Mock what you do not own and cannot control (payment providers, email, other teams' services). Use real objects for your own simple classes, like Pricing: the tests above use the real one.
  • Prefer a fake when you need to check state afterwards, and a mock when the interaction itself is the behaviour (the amount charged).
  • Verify the calls that matter, not every call. Tests that check every internal call break on every refactor.
  • If a test needs ten mocks, the code has too many dependencies: that is design feedback.

Check it works

A unit test suite is worth its name if it catches a real logic bug. Plant one: in CheckoutService.checkout, move the line that saves the order above the line that charges the payment, so orders are saved before the payment is known. Run the tests.

Two tests fail: the declined payment and the provider error both find an order in the fake that should not be there. Put the lines back and all 6 pass.

Test
mvn test
# or: pytest -q
You should see
FAILED tests/test_checkout.py::test_a_declined_payment_saves_nothing
FAILED tests/test_checkout.py::test_a_provider_error_is_not_swallowed
2 failed, 4 passed

(Java: Tests run: 6, Failures: 2)

Troubleshooting

Mockito: UnnecessaryStubbingException.

A test stubbed a call it never made. Strict stubs flag it so stale setup does not pile up: remove the stub, or stub only in the tests that need it.

Mockito: Wanted but not invoked / Argument(s) are different!.

The verify did not match. The message shows the actual call: often the amount (a total without shipping) or the reference.

Python: a mock accepts calls with wrong arguments.

You used a plain Mock(). Use create_autospec(TheClass, instance=True) so calls are checked against the real signature.

Tests depend on today's date.

Something calls LocalDate.now() or date.today() directly. Inject a Clock (or a today function) and fix it in tests.

Java warns about a dynamically loaded agent.

Mockito's inline mock maker on newer JDKs prints this warning; tests still run. Teams add Mockito as a -javaagent in Surefire's argLine to silence it.

What changes in production

  • Developers and SDETs write unit tests like these next to the code; they run on every commit in seconds and form the base of the test pyramid.
  • Services are designed with injected dependencies so they can be tested this way; a class that is hard to test is usually hard to change too.
  • Mocks are kept for boundaries you do not own; your own simple classes are used for real, which keeps tests honest.
  • Mocked boundaries are backed by contract or integration tests, so a mock never drifts silently from the real service.

Interview angle

“What is the difference between a mock, a stub and a fake, and when do you use each?”

A stub returns canned answers so the code under test can run (approve this payment). A mock is a stub you also verify, because the interaction is the behaviour (the provider was charged exactly 4999 cents, once). A fake is a working lightweight implementation, like an in-memory repository, used when you want to check state afterwards. I mock what I do not own, such as a payment provider or time, use real objects for my own simple classes, verify only the calls that matter, and back every mocked boundary with contract or integration tests.

Practice

These run in your browser and check your answer.

Write a fake

Write InMemoryOrders, a fake order store with save(order) and find_all(). find_all() must return a copy, so a test cannot change the store by changing the list it got back.

Exercise
class InMemoryOrders:
    def __init__(self):
        self._saved = []

    def save(self, order):
        self._saved.append(order)

    def find_all(self):
        return self._saved  # not a copy!
Hint

Return list(self._saved) instead of the list itself.

The full project

Every file from this lab, as it is after the last step.

Download Java project (.zip) Download Python project (.zip)