These are the notes for Low-Level Design (LLD) episode 53. In episode 52 every refactoring leaned on a home-made check method; now we make testing real. We invent unit testing and Arrange-Act-Assert, discover why some classes are almost impossible to test (a flaky test that depends on the clock, a test run that charges real money), and fix them with seams: injecting clocks and random generators and testing time-dependent code. Then test doubles (dummy, stub, fake, mock, spy), JUnit 5 (@Test, assertions, assertThrows, @BeforeEach, parameterized tests), Mockito (when-thenReturn, verify, argument captors), and TDD with red-green-refactor.
How the code was run: compiler programs with javac Main.java && java -cp . Main (Java 21). JUnit and Mockito tests with the Ubuntu packages junit5 5.10.1 (console launcher 1.9.1) and libmockito-java 2.23.0 on OpenJDK 21.0.12, using the JUnit console launcher (java -jar junit-platform-console-standalone.jar execute --select-class BillTest). All outputs are real.
1. The real-life idea: testing in Ravi's kitchen
| In the kitchen | In code |
|---|---|
| Taste the dal alone, not the whole thali | Unit test: check one small piece automatically |
| A stunt double takes the fall for the star | Test double: stands in for a real object that is dangerous or slow |
| A kitchen timer set by hand to practise the 5 pm rush at noon | Injected clock: test any time of day |
| Write down the taste you want, then cook until it matches | TDD: write the test first, then the code |
2. What a unit test is
- A unit is the smallest piece worth testing on its own: usually one class or one method.
- A unit test is a small program that runs a unit and checks the result automatically: the test decides PASS or FAIL, not your eyes.
- Good unit tests are fast (milliseconds, so you run hundreds after every change) and repeatable (the same result every run, on any machine, at any hour).
- Every test has three parts, Arrange-Act-Assert: Arrange the objects and inputs, Act by calling the one thing under test, Assert the result. An assertion is a line that says "this must be true, or the test fails".
- Testability is a design property: a testable class is easy to set up and hides nothing that the test can't control.
3. The problem: a test that depends on the time
import java.time.*;
class HappyHour {
double price(double food) {
LocalTime now = LocalTime.now(); // reads the real clock inside
boolean happy = !now.isBefore(LocalTime.of(16, 0))
&& now.isBefore(LocalTime.of(18, 0));
return happy ? food * 0.8 : food; // 20% off from 4 to 6 pm
}
}
public class Main {
static void check(String name, double expected, double actual) {
System.out.println((expected == actual ? "PASS " : "FAIL ") + name
+ ": expected " + expected + ", got " + actual);
}
public static void main(String[] args) {
System.out.println("clock says " + LocalTime.now().withNano(0));
check("happy hour is 20% off", 80.0, new HappyHour().price(100));
}
}
Real output in the video (the machine's clock said 23:44, outside 4–6 pm):
clock says 23:44:08
FAIL happy hour is 20% off: expected 80.0, got 100.0
Run it at 5 pm and it passes. A test whose result changes without the code changing is a flaky test. And there's no way to test the boundary "6 pm sharp".
4. Seams: injecting clocks and random generators
The method has a hidden dependency: it reaches out and grabs the real clock. A dependency is anything a class needs from outside to do its job. The same trap appears with new Random(), System.currentTimeMillis() and new UpiGateway() inside a class.
A seam is a place where you can change what the code does without editing that code, like a plug socket that lets you plug in a different appliance without rewiring the house. We create seams with dependency injection (episode 16): the class receives its dependencies, usually in the constructor.
Testing time-dependent code with java.time.Clock
import java.time.*;
class HappyHour {
private final Clock clock; // the seam
HappyHour(Clock clock) { this.clock = clock; }
double price(double food) {
LocalTime now = LocalTime.now(clock); // ask the injected clock
boolean happy = !now.isBefore(LocalTime.of(16, 0))
&& now.isBefore(LocalTime.of(18, 0));
return happy ? food * 0.8 : food;
}
}
public class Main {
static void check(String name, double expected, double actual) {
System.out.println((expected == actual ? "PASS " : "FAIL ") + name
+ ": expected " + expected + ", got " + actual);
}
static Clock at(int hour, int minute) { // a clock stopped at a chosen time
ZoneId india = ZoneId.of("Asia/Kolkata");
Instant instant = LocalDate.of(2026, 11, 9).atTime(hour, minute).atZone(india).toInstant();
return Clock.fixed(instant, india);
}
public static void main(String[] args) {
check("5 pm is happy hour", 80.0, new HappyHour(at(17, 0)).price(100));
check("6 pm sharp is over", 100.0, new HappyHour(at(18, 0)).price(100));
check("4 pm sharp counts", 80.0, new HappyHour(at(16, 0)).price(100));
// production code: new HappyHour(Clock.systemDefaultZone())
}
}
Output (real):
PASS 5 pm is happy hour: expected 80.0, got 80.0
PASS 6 pm sharp is over: expected 100.0, got 100.0
PASS 4 pm sharp counts: expected 80.0, got 80.0
LocalTime.now(clock)asks the injected clock instead of the system clock.Clock.fixed(instant, zone)is a clock stopped at one moment: perfect for tests.- In production:
new HappyHour(Clock.systemDefaultZone()). - Boundaries are pinned: 4 pm counts, 6 pm doesn't.
Injecting randomness
import java.util.Random;
import java.util.function.IntSupplier;
class LuckyDraw {
private final IntSupplier dice; // the seam
LuckyDraw(IntSupplier dice) { this.dice = dice; }
boolean wins() { return dice.getAsInt() == 6; }
}
public class Main {
static void check(String name, boolean expected, boolean actual) {
System.out.println((expected == actual ? "PASS " : "FAIL ") + name);
}
public static void main(String[] args) {
check("a six wins", true, new LuckyDraw(() -> 6).wins()); // test: fixed dice
check("a three loses", false, new LuckyDraw(() -> 3).wins());
Random seeded = new Random(42); // same seed = same sequence
LuckyDraw a = new LuckyDraw(() -> seeded.nextInt(6) + 1);
Random again = new Random(42);
LuckyDraw b = new LuckyDraw(() -> again.nextInt(6) + 1);
check("seeded draws repeat", a.wins() == b.wins() && a.wins() == b.wins(), true);
Random real = new Random(); // production
System.out.println("production draw: " + new LuckyDraw(() -> real.nextInt(6) + 1).wins() + " (varies)");
}
}
Output (real; the last line varies from run to run because it uses a real Random):
PASS a six wins
PASS a three loses
PASS seeded draws repeat
production draw: false (varies)
Pass in an IntSupplier (any "give me an int" function) or a Random. Tests pass a fixed function (() -> 6) or a Random with a fixed seed (the starting number of a pseudo-random sequence: the same seed always produces the same sequence).
5. The problem: a test run that charges real money
class UpiGateway { // the real thing
boolean charge(String customer, long rupees) {
System.out.println(" REAL CHARGE: Rs " + rupees + " taken from " + customer);
return true;
}
}
class SmsSender {
void send(String phone, String text) { System.out.println(" REAL SMS to " + phone + ": " + text); }
}
class OrderService {
private final UpiGateway gateway = new UpiGateway(); // created inside: no way to swap
private final SmsSender sms = new SmsSender();
String place(String customer, String phone, long rupees) {
if (!gateway.charge(customer, rupees)) return "payment failed";
sms.send(phone, "Order confirmed: Rs " + rupees);
return "confirmed";
}
}
public class Main {
public static void main(String[] args) { // "just a test"
System.out.println("test 1: " + new OrderService().place("Asha", "9876543210", 250));
System.out.println("test 2: " + new OrderService().place("Asha", "9876543210", 250));
}
}
Output (real):
REAL CHARGE: Rs 250 taken from Asha
REAL SMS to 9876543210: Order confirmed: Rs 250
test 1: confirmed
REAL CHARGE: Rs 250 taken from Asha
REAL SMS to 9876543210: Order confirmed: Rs 250
test 2: confirmed
OrderService creates its own gateway and SMS sender with new, so there is no seam. Every test run takes a customer's money, needs the network, is slow, and you can't test "payment declined" because you can't make the real gateway say no.
6. Test doubles
A test double is any object that replaces a real one in a test (named after the stunt double). The five kinds, as defined by Gerard Meszaros and quoted in Martin Fowler's article TestDouble:
| Kind | Definition | Example here |
|---|---|---|
| Dummy | Passed around but never actually used | An AuditLog that throws if anyone calls it |
| Stub | Provides canned answers to calls made during the test | A gateway that always says "approved" |
| Spy | A stub that also records how it was called | An SMS sender that stores every message in a list |
| Fake | Has a working implementation, but takes a shortcut unfit for production | An in-memory repository instead of a database |
| Mock | Pre-programmed with expectations: the calls it is expected to receive | A Mockito mock checked with verify(...) |
Dummy, stubs and a spy, by hand
import java.util.*;
interface PaymentGateway { boolean charge(String customer, long rupees); }
interface SmsSender { void send(String phone, String text); }
interface AuditLog { void write(String line); }
class OrderService {
private final PaymentGateway gateway; private final SmsSender sms;
OrderService(PaymentGateway gateway, SmsSender sms, AuditLog log) { // injected
this.gateway = gateway; this.sms = sms; } // log: only refunds use it
String place(String customer, String phone, long rupees) {
if (rupees <= 0) return "invalid amount";
if (!gateway.charge(customer, rupees)) return "payment failed";
sms.send(phone, "Order confirmed: Rs " + rupees);
return "confirmed";
}
}
class SpySms implements SmsSender { // SPY: records how it was called
final List<String> sent = new ArrayList<>();
public void send(String phone, String text) { sent.add(phone + ": " + text); }
}
public class Main {
public static void main(String[] args) {
PaymentGateway approves = (c, r) -> true, declines = (c, r) -> false; // STUBS
AuditLog dummy = line -> { throw new AssertionError("unused"); }; // DUMMY
SpySms sms = new SpySms();
System.out.println(new OrderService(approves, sms, dummy).place("Asha", "9876543210", 250));
System.out.println(new OrderService(declines, sms, dummy).place("Ravi", "9123456780", 900));
System.out.println(new OrderService(approves, sms, dummy).place("Neha", "9988776655", 0));
System.out.println("SMS sent: " + sms.sent);
}
}
Output (real):
confirmed
payment failed
invalid amount
SMS sent: [9876543210: Order confirmed: Rs 250]
The declined case, impossible before, took one line. The dummy never threw, which proves place() doesn't touch the log.
A fake
import java.util.*;
record Order(String id, String customer, long rupees) { }
interface OrderRepository { // the boundary: a database in production
void save(Order order);
Optional<Order> findById(String id);
List<Order> findByCustomer(String customer);
}
class InMemoryOrderRepository implements OrderRepository { // FAKE: really works, but only in memory
private final Map<String, Order> rows = new LinkedHashMap<>();
public void save(Order order) { rows.put(order.id(), order); }
public Optional<Order> findById(String id) { return Optional.ofNullable(rows.get(id)); }
public List<Order> findByCustomer(String customer) {
return rows.values().stream().filter(o -> o.customer().equals(customer)).toList();
}
}
class LoyaltyService {
private final OrderRepository orders;
LoyaltyService(OrderRepository orders) { this.orders = orders; }
boolean isRegular(String customer) { return orders.findByCustomer(customer).size() >= 3; }
}
public class Main {
public static void main(String[] args) {
OrderRepository repo = new InMemoryOrderRepository();
for (int i = 1; i <= 3; i++) repo.save(new Order("A" + i, "Asha", 100 * i));
repo.save(new Order("R1", "Ravi", 90));
LoyaltyService loyalty = new LoyaltyService(repo);
System.out.println("Asha regular? " + loyalty.isRegular("Asha") + ", Ravi regular? " + loyalty.isRegular("Ravi"));
System.out.println("find A2: " + repo.findById("A2").orElseThrow());
}
}
Output (real):
Asha regular? true, Ravi regular? false
find A2: Order[id=A2, customer=Asha, rupees=200]
7. JUnit 5
A test framework is ready-made code that finds and runs your tests and reports the results. The standard one for Java is JUnit 5. Its documentation describes it as JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage, and says it requires Java 8 or higher at runtime:
- JUnit Platform: finds and runs tests (used by IDEs, Maven, Gradle and the console launcher).
- JUnit Jupiter: the API you write tests with (
@Test,Assertions...). - JUnit Vintage: runs old JUnit 3 and JUnit 4 tests on the platform.
| Feature | What it does |
|---|---|
@Test |
Marks a method as a test. An annotation is a label starting with @ that tools read |
assertEquals(expected, actual) |
Fails if they differ; expected first. For doubles add a tolerance: assertEquals(189.0, total, 0.001) |
assertTrue(cond), assertFalse(cond), assertNull(x) |
Simple checks |
assertThrows(Type.class, () -> ...) |
Fails unless the lambda throws that exception; returns it so you can check the message |
@BeforeEach |
Runs before every test: fresh objects, so tests never affect each other |
@ParameterizedTest + @CsvSource |
Runs one test method once per row of data |
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class BillCalculator {
double total(double food, boolean isMember) {
if (food < 0) throw new IllegalArgumentException("food can't be negative: " + food);
return (isMember ? food * 0.9 : food) * 1.05;
}
}
class BillTest {
BillCalculator bill;
@BeforeEach void setUp() { bill = new BillCalculator(); } // fresh object for every test
@Test void memberGetsTenPercentOff() {
double food = 200; // Arrange
double total = bill.total(food, true); // Act
assertEquals(189.0, total, 0.001); // Assert
}
@Test void negativeFoodIsRejected() {
var e = assertThrows(IllegalArgumentException.class, () -> bill.total(-5, false));
assertEquals("food can't be negative: -5.0", e.getMessage());
}
@ParameterizedTest
@CsvSource({"100, false, 105.0", "100, true, 94.5", "0, true, 0.0"})
void totals(double food, boolean member, double expected) {
assertEquals(expected, bill.total(food, member), 0.001);
}
@Test void forgotTheDiscount() { // a test that fails on purpose
assertEquals(189.0, bill.total(200, false), 0.001);
}
}
Real output (JUnit console launcher, tree view, shortened):
╷
└─ JUnit Jupiter ✔
└─ BillTest ✔
├─ totals(double, boolean, double) ✔
│ ├─ [1] 100, false, 105.0 ✔
│ ├─ [2] 100, true, 94.5 ✔
│ └─ [3] 0, true, 0.0 ✔
├─ negativeFoodIsRejected() ✔
├─ forgotTheDiscount() ✘ expected: <189.0> but was: <210.0>
└─ memberGetsTenPercentOff() ✔
...
[ 5 tests successful ]
[ 1 tests failed ]
The failure explains itself: which test, the expected value and the actual value. In real projects your build tool (Maven or Gradle) or the IDE's run button runs the tests; the console launcher is the same JUnit Platform from the command line.
8. Mockito
Mockito is a Java library that creates test doubles for you, so you don't write a stub class for every interface.
| Call | Meaning |
|---|---|
mock(PaymentGateway.class) |
A double that implements the type; by default does nothing and returns empty answers (false, 0, null) |
when(gateway.charge("Asha", 250)).thenReturn(true) |
Stub a call: when asked this, answer that |
verify(sms).send(...) / verify(sms, times(2)) / verify(sms, never()) |
Check a call happened (once, twice, never) |
eq(...), anyString() |
Argument matchers: "exactly this" / "any string" |
ArgumentCaptor<String> text = ArgumentCaptor.forClass(String.class) |
An argument captor catches the actual argument passed, so you can check it |
import org.junit.jupiter.api.*;
import org.mockito.ArgumentCaptor;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
interface PaymentGateway { boolean charge(String customer, long rupees); }
interface SmsSender { void send(String phone, String text); }
class OrderService {
private final PaymentGateway gateway;
private final SmsSender sms;
OrderService(PaymentGateway gateway, SmsSender sms) { this.gateway = gateway; this.sms = sms; }
String place(String customer, String phone, long rupees) {
if (!gateway.charge(customer, rupees)) return "payment failed";
sms.send(phone, "Order confirmed: Rs " + rupees);
return "confirmed";
}
}
class OrderServiceTest {
PaymentGateway gateway = mock(PaymentGateway.class); // no real money moves
SmsSender sms = mock(SmsSender.class); // no real SMS goes out
OrderService service = new OrderService(gateway, sms);
@Test void paidOrderSendsOneConfirmation() {
when(gateway.charge("Asha", 250)).thenReturn(true); // stub the answer
assertEquals("confirmed", service.place("Asha", "9876543210", 250));
ArgumentCaptor<String> text = ArgumentCaptor.forClass(String.class);
verify(sms, times(1)).send(eq("9876543210"), text.capture()); // check the call
assertEquals("Order confirmed: Rs 250", text.getValue());
}
@Test void failedPaymentSendsNoSms() {
when(gateway.charge("Ravi", 900)).thenReturn(false);
assertEquals("payment failed", service.place("Ravi", "9123456780", 900));
verify(sms, never()).send(anyString(), anyString());
}
@Test void smsSentTwiceIsCaught() { // fails on purpose
when(gateway.charge("Neha", 120)).thenReturn(true);
service.place("Neha", "9988776655", 120);
verify(sms, times(2)).send(anyString(), anyString());
}
}
Real output (shortened):
╷
└─ JUnit Jupiter ✔
└─ OrderServiceTest ✔
├─ smsSentTwiceIsCaught() ✘
│ smsSender.send(<any string>, <any string>);
│ Wanted 2 times:
│ -> at OrderServiceTest.smsSentTwiceIsCaught(OrderServiceTest.java:38)
│ But was 1 time:
│ -> at OrderService.place(OrderServiceTest.java:14)
├─ paidOrderSendsOneConfirmation() ✔
└─ failedPaymentSendsNoSms() ✔
...
[ 2 tests successful ]
[ 1 tests failed ]
Mockito checks interactions (which calls happened, with which arguments), not just return values; the failure shows where the call was expected and where it actually happened.
Advice: mock the boundaries of your system (payments, SMS, email, time, HTTP, databases); don't mock simple values (just create a real Money); wrap third-party libraries in your own small interface and mock that; and don't verify every internal call, or your tests will break on every refactoring.
9. TDD: red, green, refactor
Test-driven development (TDD) means writing the test before the code, in a short cycle:
- Red: write a test for the next small behaviour and watch it fail (a compile error counts). Seeing red proves the test can fail.
- Green: write the simplest code that makes it pass. No code for features nobody asked for.
- Refactor: clean up the code (episode 52) while all tests stay green.
Bonus: code written test-first is testable by design, because the test was its first user.
Red (tests first, Coupon doesn't exist yet):
public class Main {
static void check(String name, Object expected, Object actual) {
System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name
+ ": expected " + expected + ", got " + actual);
}
public static void main(String[] args) { // the tests come FIRST
check("CHAI10 takes Rs 10 off", 190L, Coupon.apply("CHAI10", 200));
check("unknown code changes nothing", 200L, Coupon.apply("FREEFOOD", 200));
}
}
Output (real):
Main.java:7: error: cannot find symbol
check("CHAI10 takes Rs 10 off", 190L, Coupon.apply("CHAI10", 200));
^
symbol: variable Coupon
location: class Main
Main.java:8: error: cannot find symbol
check("unknown code changes nothing", 200L, Coupon.apply("FREEFOOD", 200));
^
symbol: variable Coupon
location: class Main
2 errors
Green, step 1 (just enough to compile; the second test pushes back):
class Coupon {
static long apply(String code, long rupees) {
return 190; // just enough to compile
}
}
public class Main {
static void check(String name, Object expected, Object actual) {
System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name
+ ": expected " + expected + ", got " + actual);
}
public static void main(String[] args) { // the tests come FIRST
check("CHAI10 takes Rs 10 off", 190L, Coupon.apply("CHAI10", 200));
check("unknown code changes nothing", 200L, Coupon.apply("FREEFOOD", 200));
}
}
Output (real):
PASS CHAI10 takes Rs 10 off: expected 190, got 190
FAIL unknown code changes nothing: expected 200, got 190
Green, step 2 (the simplest real rule):
class Coupon {
static long apply(String code, long rupees) {
if (code.equals("CHAI10")) return rupees - 10; // the simplest real rule
return rupees;
}
}
public class Main {
static void check(String name, Object expected, Object actual) {
System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name
+ ": expected " + expected + ", got " + actual);
}
public static void main(String[] args) { // the tests come FIRST
check("CHAI10 takes Rs 10 off", 190L, Coupon.apply("CHAI10", 200));
check("unknown code changes nothing", 200L, Coupon.apply("FREEFOOD", 200));
}
}
Output (real):
PASS CHAI10 takes Rs 10 off: expected 190, got 190
PASS unknown code changes nothing: expected 200, got 200
Refactor (rules become data; still green):
import java.util.Map;
class Coupon {
private static final Map<String, Long> RUPEES_OFF = Map.of("CHAI10", 10L, "THALI50", 50L);
static long apply(String code, long rupees) { // refactored: rules are data
long off = RUPEES_OFF.getOrDefault(code, 0L);
return Math.max(0, rupees - off);
}
}
public class Main {
static void check(String name, Object expected, Object actual) {
System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name
+ ": expected " + expected + ", got " + actual);
}
public static void main(String[] args) { // the tests come FIRST
check("CHAI10 takes Rs 10 off", 190L, Coupon.apply("CHAI10", 200));
check("unknown code changes nothing", 200L, Coupon.apply("FREEFOOD", 200));
}
}
Output (real):
PASS CHAI10 takes Rs 10 off: expected 190, got 190
PASS unknown code changes nothing: expected 200, got 200
Common mistakes
| Mistake | What you see (real) | Why | Fix |
|---|---|---|---|
LocalTime.now() inside the class |
FAIL happy hour is 20% off: expected 80.0, got 100.0 (only sometimes) |
Flaky: depends on the clock | Inject a Clock; Clock.fixed in tests |
new UpiGateway() inside the class |
REAL CHARGE: Rs 250 taken from Asha on every run |
No seam | Constructor injection + a test double |
assertEquals(actual, expected) |
swappedArguments() ✘ expected: <210.0> but was: <189.0> (the message lies) |
Wrong argument order | Expected first |
| Comparing doubles exactly | exactDoubles() ✘ expected: <0.3> but was: <0.30000000000000004> |
Binary fractions | assertEquals(0.3, x, 1e-9) |
| A test that never failed | Nothing: it may check nothing | No red step | See it fail first (TDD) |
| Tests sharing one object | Tests pass alone, fail together | State leaks between tests | @BeforeEach creates fresh objects |
| Mocking everything | Tests break on every refactoring | Tests know the inside | Mock only the boundaries |
The two JUnit lines above come from this real test class:
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
class MistakeTest {
@Test void swappedArguments() { double actual = 200 * 1.05; assertEquals(actual, 189.0); } // actual first: wrong
@Test void exactDoubles() { assertEquals(0.3, 0.1 + 0.2); }
}
╷
└─ JUnit Jupiter ✔
└─ MistakeTest ✔
├─ swappedArguments() ✘ expected: <210.0> but was: <189.0>
└─ exactDoubles() ✘ expected: <0.3> but was: <0.30000000000000004>
Mini project: a parking fee, test-first
Rules: the first 15 minutes are free; then Rs 20 for every started hour; at most Rs 150 a day; negative minutes are rejected. Each check below was written first and seen to fail before the code that makes it pass was added.
class ParkingFee {
private static final int FREE_MINUTES = 15, RUPEES_PER_HOUR = 20, DAILY_CAP = 150;
static int fee(int minutes) {
if (minutes < 0) throw new IllegalArgumentException("minutes can't be negative: " + minutes);
if (minutes <= FREE_MINUTES) return 0;
int hours = (minutes + 59) / 60; // every started hour counts
return Math.min(DAILY_CAP, hours * RUPEES_PER_HOUR);
}
}
public class Main {
static void check(String name, int expected, int actual) {
System.out.println((expected == actual ? "PASS " : "FAIL ") + name + ": expected " + expected + ", got " + actual);
}
public static void main(String[] args) { // written one at a time, each one red first
check("first 15 minutes are free", 0, ParkingFee.fee(15));
check("16 minutes is one hour", 20, ParkingFee.fee(16));
check("61 minutes is two hours", 40, ParkingFee.fee(61));
check("a whole day is capped", 150, ParkingFee.fee(24 * 60));
try { ParkingFee.fee(-1); System.out.println("FAIL negative accepted"); }
catch (IllegalArgumentException e) { System.out.println("PASS negative rejected: " + e.getMessage()); }
}
}
Output (real):
PASS first 15 minutes are free: expected 0, got 0
PASS 16 minutes is one hour: expected 20, got 20
PASS 61 minutes is two hours: expected 40, got 40
PASS a whole day is capped: expected 150, got 150
PASS negative rejected: minutes can't be negative: -1
The same tests in JUnit 5 would be one @ParameterizedTest with @CsvSource({"15, 0", "16, 20", "61, 40", "1440, 150"}) plus one assertThrows.
Practice
1. class Greeting { String greet() { int h = LocalTime.now().getHour(); return h < 12 ? "Good morning" : "Good evening"; } }. Make it testable and test 11:59 and 12:00.
Answer
Inject a Clock: Greeting(Clock clock) and LocalTime.now(clock).getHour(). In tests, build Clock.fixed(...) at 11:59 and at 12:00 (exactly as at(hour, minute) in section 4) and assert "Good morning" and "Good evening".
2. Name the double: (a) a Map-based UserRepository used in tests; (b) a Clock that always says 5 pm; (c) a Logger passed to a constructor but not used by the method under test; (d) an EmailSender that stores sent emails in a list for the test to inspect.
Answer
(a) fake; (b) stub; (c) dummy; (d) spy.
3. With Mockito, write a test that a refund of Rs 0 never calls the gateway.
Answer
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
interface RefundGateway { boolean refund(String customer, long rupees); }
class RefundService {
private final RefundGateway gateway;
RefundService(RefundGateway gateway) { this.gateway = gateway; }
String refund(String customer, long rupees) {
if (rupees <= 0) return "nothing to refund"; // guard: never call the gateway
return gateway.refund(customer, rupees) ? "refunded" : "refund failed";
}
}
class RefundTest {
@Test void zeroRefundNeverCallsGateway() {
RefundGateway gateway = mock(RefundGateway.class);
assertEquals("nothing to refund", new RefundService(gateway).refund("Asha", 0));
verify(gateway, never()).refund(anyString(), anyLong());
}
}
Real output:
╷
└─ JUnit Jupiter ✔
└─ RefundTest ✔
└─ zeroRefundNeverCallsGateway() ✔
4. Why must a TDD cycle start with a failing test?
Answer
To prove the test can fail. A test that passes before the code exists checks nothing (a wrong assertion, a test not being run, a typo in the setup).
5. Your test passes alone but fails when the whole class runs. Likely cause?
Answer
Shared mutable state between tests, e.g. a static list or one object reused by every test. Create fresh objects in @BeforeEach and avoid static state.
Quick quiz
class LuckyDraw {
boolean wins() {
return new Random().nextInt(6) == 5;
}
}
What makes this class testable? (a) Make wins() static (b) Pass a Random (or IntSupplier) into the constructor (c) Run the test 100 times (d) Add a comment
Answer
(b). new Random() inside is a hidden dependency. Injecting it creates a seam: the test passes a fixed generator such as () -> 5 and gets the same answer every run.
Interview questions
- What makes a class hard to test? Hidden dependencies (
newof collaborators, static calls,now(),new Random()), global state, doing too much, side effects in constructors. - What is a seam? A place where behaviour can be changed without editing the code, usually a constructor parameter typed by an interface.
- Stub vs mock? A stub supplies canned answers (state checked afterwards); a mock is set up with expected calls and the test verifies the interactions.
- Fake vs stub? A fake really works (in-memory DB); a stub only returns pre-set answers.
- How do you test time-dependent code in Java? Inject
java.time.Clock; useClock.fixed(orClock.offset) in tests. - What's the Arrange-Act-Assert pattern? Set up, call the unit once, check the result: three visible blocks in every test.
- Explain red-green-refactor. Failing test, simplest passing code, clean up while green.
- What should you not mock? Value objects, the class under test itself, and code you don't own (wrap it first).
Glossary
| Term | Meaning, with an example |
|---|---|
| Unit | The smallest piece worth testing alone: the HappyHour class |
| Unit test | Automatic check of one unit: check("5 pm is happy hour", 80.0, ...) |
| Assertion | A line that must be true or the test fails: assertEquals(189.0, total, 0.001) |
| Arrange-Act-Assert | Set up, call, check: the three parts of every test |
| Flaky test | A test whose result changes without the code changing: passes only between 4 and 6 pm |
| Testability | How easy a class is to set up and check in a test |
| Dependency | Something a class needs from outside: a clock, a payment gateway |
| Hidden dependency | A dependency the class grabs itself, out of the test's control: LocalTime.now() inside a method |
| Seam | A place where behaviour can be swapped without editing the code: a Clock constructor parameter |
| Dependency injection | Giving a class its dependencies from outside, e.g. via the constructor |
Clock |
java.time class that tells the time; Clock.fixed(...) stops it at one moment |
| Seed | The starting number of a pseudo-random sequence: new Random(42) repeats the same numbers |
IntSupplier |
A function that returns an int: () -> 6 |
| Test double | Any stand-in for a real object in a test |
| Dummy | Passed in but never used |
| Stub | Gives canned answers: a gateway that always approves |
| Spy | A stub that records how it was called: SpySms.sent |
| Fake | A working shortcut implementation: InMemoryOrderRepository |
| Mock | Pre-programmed with expected calls, verified by the test: verify(sms, times(1)).send(...) |
| Test framework | Ready-made code that finds, runs and reports tests: JUnit |
| JUnit 5 | The standard Java test framework: Platform + Jupiter + Vintage |
| JUnit Platform / Jupiter / Vintage | The runner / the API you write tests with / support for old JUnit 3-4 tests |
| Annotation | A label starting with @ that tools read: @Test |
@Test |
Marks a test method |
assertThrows |
Asserts that code throws a given exception and returns it |
@BeforeEach |
Runs before every test to create fresh objects |
| Parameterized test | One test method run for many inputs: @ParameterizedTest @CsvSource({...}) |
| Console launcher | JUnit's command-line runner: java -jar junit-platform-console-standalone.jar execute ... |
| Mockito | Java library that creates and verifies test doubles |
when(...).thenReturn(...) |
Mockito stubbing: what a call should answer |
verify(...) |
Mockito check that a call happened: times(2), never() |
| Argument matcher | eq("x"), anyString(): describe which arguments match |
| Argument captor | Catches the actual argument of a call: ArgumentCaptor.forClass(String.class) |
| Interaction testing | Checking which calls a unit made to its collaborators |
| Boundary | Where your code meets the outside world: payments, SMS, time, HTTP, database |
| TDD | Test-driven development: write the test before the code |
| Red-green-refactor | Failing test → simplest passing code → clean up while green |
| Characterization test | A test that pins down what existing code does today (episode 52) |
Summary
- A unit test checks one small piece automatically, fast and repeatably; write it as Arrange-Act-Assert.
- Hidden dependencies (the clock,
Random,new Gateway()) make tests flaky or dangerous; a seam made by injecting them fixes it (Clock.fixed, a seededRandom, anIntSupplier). - Test doubles: dummy, stub, spy, fake, mock.
- JUnit 5 (
@Test,assertEqualsexpected-first,assertThrows,@BeforeEach,@ParameterizedTest) runs tests and explains failures. - Mockito (
mock,when-thenReturn,verify,times/never,ArgumentCaptor) creates and checks doubles; mock the boundaries only. - TDD: red, green, refactor; code written test-first is testable by design.
Next episode: Error handling, validation and class API design: exceptions vs error codes, fail fast, guard clauses, domain exceptions, a Result type, null-safety conventions and minimal public APIs.