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
What you will build
A small checkout module and 6 unit tests that run in milliseconds, with no network, database or real clock:
CheckoutServiceprices 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
- Your first Java test project: this lab reuses its
PricingandCouponclasses (Python:pricing.py). - The ideas behind this lab: Mocks, stubs and fakes and Unit testing with JUnit and pytest.
- You do not need ShopRung running: unit tests never touch the real system.
Setup
S1Java 21 and Maven, or Python 3.12
From lab 4. Check the versions for the path you take.
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.
# 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# 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# Java
mkdir shoprung-checkout\src\main\java\dev\algorung\shop, shoprung-checkout\src\test\java\dev\algorung\shop
# Python
mkdir shoprung-checkout-py\shop, shoprung-checkout-py\tests; cd shoprung-checkout-py; py -m venv .venv; .venv\Scripts\Activate.ps1 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.
<?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> - Mockito plus
MockitoExtensionfor JUnit 5. It bringsmockito-core.line 26
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);
}
} - From lab 4: subtotal, discount, shipping, total, all in cents.line 31
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
}
} - Expires on 31 December 2025: the clock decides whether it applies.line 10
pytest==8.3.4 [pytest]
testpaths = tests
pythonpath = . - So tests can
import shop.line 3
"""ShopRung's checkout logic, for unit testing.""" """ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Python.
Every amount is whole cents in an int: $50.00 is 5000. No float, so no rounding surprises.
"""
from dataclasses import dataclass
from datetime import date
FREE_SHIPPING_FROM = 7_500 # $75.00, after the discount
SHIPPING = 499 # $4.99
@dataclass(frozen=True)
class Coupon:
code: str
percent: bool
amount: int # a percent, or cents
min_subtotal: int # cents
expires_on: date | None = None
COUPONS = {
"SAVE10": Coupon("SAVE10", True, 10, 5_000), # 10% off from $50.00
"FLAT5": Coupon("FLAT5", False, 500, 2_000), # $5.00 off from $20.00
"WELCOME15": Coupon("WELCOME15", True, 15, 0, date(2025, 12, 31)), # expired
}
@dataclass(frozen=True)
class Totals:
subtotal: int
discount: int
shipping: int
total: int
def money(cents: int) -> str:
"""1250 becomes "$12.50" (PRICE-1)."""
if cents < 0:
raise ValueError(f"cents must not be negative: {cents}")
return f"${cents // 100}.{cents % 100:02d}"
def shipping(after_discount: int) -> int:
"""$4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing."""
if after_discount == 0:
return 0
return 0 if after_discount >= FREE_SHIPPING_FROM else SHIPPING
def coupon(code: str | None) -> Coupon:
"""Finds a coupon. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7)."""
c = (code or "").strip().upper()
if c not in COUPONS:
raise ValueError(f"No coupon called {c or '(empty)'}")
return COUPONS[c]
def problem(c: Coupon, subtotal: int, today: date) -> str | None:
"""Why the coupon cannot be used, or None when it can."""
if c.expires_on and today > c.expires_on:
return "This coupon has expired"
if subtotal < c.min_subtotal:
return f"This coupon needs a subtotal of at least {money(c.min_subtotal)}"
return None
def discount(c: Coupon, subtotal: int) -> int:
"""The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6)."""
if c.percent:
return (subtotal * c.amount + 50) // 100
return min(c.amount, subtotal) # a fixed amount never makes the total negative
def totals(subtotal: int, c: Coupon | None, today: date) -> Totals:
"""Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8)."""
if subtotal < 0:
raise ValueError(f"subtotal must not be negative: {subtotal}")
off = discount(c, subtotal) if c and problem(c, subtotal, today) is None else 0
ship = shipping(subtotal - off)
return Totals(subtotal, off, ship, subtotal - off + ship) - From lab 4: subtotal, discount, shipping, total, all in cents.line 74
Python version of this step:
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.
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);
} - One method: easy to replace in tests.line 11
package dev.algorung.shop;
/** A placed and paid order. */
public record Order(String ref, String customer, long totalCents, String coupon) {} 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();
} 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);
}
} 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;
}
} - Dependencies come in from outside: that is what makes this testable.line 17
- Never
LocalDate.now(): the clock is injected.line 27 - Declined: stop before saving anything.line 32
- Saved only after an approved payment.line 36
"""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.
"""
from dataclasses import dataclass
from datetime import date
from itertools import count
from typing import Callable, Protocol
from shop import pricing
@dataclass(frozen=True)
class PaymentResult:
approved: bool
reason: str | None = None
class PaymentGateway(Protocol):
def charge(self, order_ref: str, amount_cents: int) -> PaymentResult: ...
@dataclass(frozen=True)
class Order:
ref: str
customer: str
total_cents: int
coupon: str | None
class OrderRepository(Protocol):
def save(self, order: Order) -> None: ...
def find_all(self) -> list[Order]: ...
class PaymentDeclined(Exception):
"""Raised when the provider says no. Nothing is saved."""
class CheckoutService:
def __init__(self, payments: PaymentGateway, orders: OrderRepository, today: Callable[[], date] = date.today):
self.payments = payments
self.orders = orders
self.today = today
self._next = count(1)
def checkout(self, customer: str, subtotal_cents: int, coupon_code: str | None) -> Order:
"""Charges the discounted total and saves the order. A declined payment saves nothing."""
if subtotal_cents <= 0:
raise ValueError("Your cart is empty")
coupon = pricing.coupon(coupon_code) if coupon_code is not None else None
totals = pricing.totals(subtotal_cents, coupon, self.today())
ref = f"ORD-{next(self._next)}"
result = self.payments.charge(ref, totals.total)
if not result.approved:
raise PaymentDeclined(f"Payment declined: {result.reason}")
order = Order(ref, customer, totals.total, coupon.code if totals.discount > 0 else None)
self.orders.save(order)
return order - A Protocol: any object with a matching
chargemethod fits.line 20 - Dependencies come in from outside.
todayis a function, so tests can fix the date.line 42 - Declined: stop before saving anything.line 57
- Saved only after an approved payment.line 61
Python version of this step:
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.
InMemoryOrderRepositoryis 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_autospecin 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,todayis a lambda that returns a fixeddate.
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.
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);
}
} - A real implementation, just without a database.line 7
"""Test doubles for checkout: a fake order store, a mock payment provider and a fixed date."""
from datetime import date
from unittest.mock import create_autospec
import pytest
from shop.checkout import CheckoutService, Order, PaymentGateway, PaymentResult
class InMemoryOrderRepository:
"""A fake: a real, working order store that keeps orders in a list instead of a database."""
def __init__(self):
self._saved: list[Order] = []
def save(self, order: Order) -> None:
self._saved.append(order)
def find_all(self) -> list[Order]:
return list(self._saved)
@pytest.fixture
def payments():
"""A mock with the same methods as PaymentGateway; approves by default."""
mock = create_autospec(PaymentGateway, instance=True)
mock.charge.return_value = PaymentResult(approved=True)
return mock
@pytest.fixture
def orders():
return InMemoryOrderRepository()
@pytest.fixture
def checkout(payments, orders):
"""'Today' is always 30 November 2026 in these tests."""
return CheckoutService(payments, orders, today=lambda: date(2026, 11, 30)) - The fake.line 10
- A mock that checks calls match the real method signatures.line 26
- A stub: the default answer, which tests can change.line 27
- The fixed clock.line 39
Python version of this step:
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.
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());
}
} - Creates the mocks and checks for unused stubs (strict stubs).line 18
- A mock: no real behaviour until you stub it.line 21
- Arrange: the stubbed answer.line 36
- Assert on the interaction: exactly this call, exactly once.line 40
def test_charges_the_discounted_total_and_saves_the_order(checkout, payments, orders):
order = checkout.checkout("alice@shoprung.test", 5_000, "save10")
payments.charge.assert_called_once_with("ORD-1", 4_999) # $50.00 - $5.00 + $4.99 shipping
assert order.total_cents == 4_999
assert order.coupon == "SAVE10"
assert len(orders.find_all()) == 1 - The fixtures arrive as parameters: the service, the mock, the fake.line 1
- Assert on the interaction: exactly this call, exactly once.line 4
Python version of this step:
mvn test [INFO] Running dev.algorung.shop.CheckoutServiceTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pip install -r requirements.txt
pytest -q . [100%] 1 passed in 0.01s
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.
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));
}
} - The answer a real provider would never give you on cue.line 53
- The fake answers "what was saved?": nothing.line 59
- Simulate a timeout or outage.line 64
- Not one call reached the provider.line 76
import pytest
from shop.checkout import PaymentDeclined, PaymentResult
def test_charges_the_discounted_total_and_saves_the_order(checkout, payments, orders):
order = checkout.checkout("alice@shoprung.test", 5_000, "save10")
payments.charge.assert_called_once_with("ORD-1", 4_999) # $50.00 - $5.00 + $4.99 shipping
assert order.total_cents == 4_999
assert order.coupon == "SAVE10"
assert len(orders.find_all()) == 1
def test_a_declined_payment_saves_nothing(checkout, payments, orders):
payments.charge.return_value = PaymentResult(approved=False, reason="card_declined")
with pytest.raises(PaymentDeclined, match="Payment declined: card_declined"):
checkout.checkout("alice@shoprung.test", 5_000, None)
assert orders.find_all() == [], "no order may be saved when payment fails"
def test_a_provider_error_is_not_swallowed(checkout, payments, orders):
payments.charge.side_effect = TimeoutError("provider timed out")
with pytest.raises(TimeoutError, match="provider timed out"):
checkout.checkout("alice@shoprung.test", 2_000, None)
assert orders.find_all() == []
def test_an_empty_cart_never_reaches_the_payment_provider(checkout, payments):
with pytest.raises(ValueError):
checkout.checkout("alice@shoprung.test", 0, None)
payments.charge.assert_not_called()
def test_an_unknown_coupon_stops_checkout_before_paying(checkout, payments):
with pytest.raises(ValueError, match="No coupon called NOPE"):
checkout.checkout("alice@shoprung.test", 5_000, "NOPE")
payments.charge.assert_not_called() - Change the stub's answer for this test only.line 16
side_effectmakes the mock raise.line 25- Not one call reached the provider.line 36
Python version of this step:
mvn test [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pytest -q ..... [100%] 5 passed in 0.02s
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).
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));
}
} - Time becomes a test input like any other.line 85
- Collects the arguments of every call.line 91
- Both edges of the expiry date in one check.line 93
from datetime import date
import pytest
from shop.checkout import CheckoutService, PaymentDeclined, PaymentResult
def test_charges_the_discounted_total_and_saves_the_order(checkout, payments, orders):
order = checkout.checkout("alice@shoprung.test", 5_000, "save10")
payments.charge.assert_called_once_with("ORD-1", 4_999) # $50.00 - $5.00 + $4.99 shipping
assert order.total_cents == 4_999
assert order.coupon == "SAVE10"
assert len(orders.find_all()) == 1
def test_a_declined_payment_saves_nothing(checkout, payments, orders):
payments.charge.return_value = PaymentResult(approved=False, reason="card_declined")
with pytest.raises(PaymentDeclined, match="Payment declined: card_declined"):
checkout.checkout("alice@shoprung.test", 5_000, None)
assert orders.find_all() == [], "no order may be saved when payment fails"
def test_a_provider_error_is_not_swallowed(checkout, payments, orders):
payments.charge.side_effect = TimeoutError("provider timed out")
with pytest.raises(TimeoutError, match="provider timed out"):
checkout.checkout("alice@shoprung.test", 2_000, None)
assert orders.find_all() == []
def test_an_empty_cart_never_reaches_the_payment_provider(checkout, payments):
with pytest.raises(ValueError):
checkout.checkout("alice@shoprung.test", 0, None)
payments.charge.assert_not_called()
def test_welcome15_works_on_its_last_day_and_not_the_day_after(payments, orders):
CheckoutService(payments, orders, today=lambda: date(2025, 12, 31)).checkout("alice", 4_000, "WELCOME15")
CheckoutService(payments, orders, today=lambda: date(2026, 1, 1)).checkout("alice", 4_000, "WELCOME15")
amounts = [c.args[1] for c in payments.charge.call_args_list]
assert amounts == [3_899, 4_499] # 15% off, then no discount
def test_an_unknown_coupon_stops_checkout_before_paying(checkout, payments):
with pytest.raises(ValueError, match="No coupon called NOPE"):
checkout.checkout("alice@shoprung.test", 5_000, "NOPE")
payments.charge.assert_not_called() - Time becomes a test input like any other.line 42
- Every call the mock received, in order.line 45
Python version of this step:
mvn test [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pytest -q ...... [100%] 6 passed in 0.02s
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.
mvn test
# or: pytest -q 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.
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.