Designing for Testability
Testable code isn't a separate quality you bolt on at the end. It's a side effect of good design, and the lack of it is one of the clearest signs of bad design. When a class is hard to test, it's usually because it does too much, reaches for hidden inputs like the clock or a global, creates its own collaborators, or mixes decisions with side effects. Fix those, and the tests become easy. Fix those, and the class also becomes easier to understand, reuse and change.
That's why this page sits among the design principles rather than in a testing section. It covers how to shape classes so they can be tested, not how to use a test framework. You'll see seams (the places where a test can swap behaviour), constructor injection, how to tame the three classic hidden inputs (time, randomness and IO), the vocabulary of test doubles, the functional core, imperative shell structure, and how to test private behaviour through public APIs.
The Dependency Injection deep dive covers containers, injection styles and anti-patterns like the service locator. This page links there rather than repeating it, and focuses on the design decisions inside a class.
Every sample was run with Java 24, Python 3.12 and TypeScript 5.8 (tsc --strict, then tsx). The Java samples use a small check helper so they fail without the -ea flag. They use hand-written test doubles rather than a mocking library, so they run anywhere and show what libraries like Mockito, unittest.mock and Jest do for you.
1. Why testability is a design property
A unit test does three things: build the object, poke it, and check what happened. Each step fails in a characteristic way when the design is poor.
| Step | What makes it hard | The underlying design problem |
|---|---|---|
| Build | The constructor connects to a database, reads a file, or needs fifteen arguments | The class creates its own collaborators, or has too many responsibilities |
| Poke | The behaviour depends on the current time, a random number, an environment variable or a global | Hidden inputs that the caller can't control |
| Check | The result is an email sent, a file written or a log line, not a return value or a state change you can read | Hidden outputs, and decisions tangled with side effects |
Michael Feathers, in Working Effectively with Legacy Code (2004), made the connection explicit: legacy code is code without tests, and most of the work of adding tests is breaking the hidden dependencies that stop you constructing and observing objects. Designing for testability means not creating those dependencies in the first place.
Testability is feedback
If you find a test hard to write, treat it as information about the design, not about the test. "I need to set up a mail server to test the price calculation" means price calculation and mail sending shouldn't be in the same class. See Cohesion, Coupling & the Law of Demeter.
2. Seams
Feathers defines a seam as a place where you can alter behaviour in your program without editing in that place. Every seam has an enabling point: the place where you choose which behaviour to use.
In object-oriented code, the most useful seam is the object seam. A class calls a method on a collaborator through an interface or base type, and the collaborator is supplied from outside. The enabling point is wherever that collaborator is created: the constructor call in production code, and the test's setup in a test.
| Kind of seam | How behaviour is swapped | Where you'll see it | Verdict |
|---|---|---|---|
| Object seam | Pass a different object implementing the same interface | Constructor and method parameters | The default. Explicit and type-checked |
| Function seam | Pass a different function | now: () => Date, rng: () => number | Lighter than an interface when there's one operation |
| Link or module seam | Swap a module at import or link time | unittest.mock.patch, jest.mock, classpath tricks | Works on code you can't change, but hides the dependency |
| Subclass-and-override seam | Subclass the class under test and override a protected method | Legacy code you're starting to test | A stepping stone, not a target design |
flowchart LR
subgraph prod["Production wiring"]
P1["main()"] -->|"new SmtpMailer()"| S1["SignupService"]
end
subgraph test["Test wiring"]
T1["test"] -->|"new RecordingMailer()"| S2["SignupService"]
end
S1 --> I["Mailer interface"]
S2 --> I
The same SignupService code runs in both. Only the enabling point differs. That's what makes it a seam.
3. Constructor injection
The simplest way to create object seams is to pass collaborators into the constructor instead of constructing them inside. This is constructor injection, the preferred form of dependency injection, and the mechanism behind the Dependency Inversion Principle.
Below, the "before" service builds a real mailer and a real repository in its constructor. To simulate what happens in a test environment, they throw, because there's no mail server or database. The service can't even be constructed in a test, let alone exercised.
import java.util.*;
// ---------- before: the service builds its own collaborators ----------
final class SmtpMailer {
SmtpMailer() { throw new IllegalStateException("no SMTP server reachable"); } // what a test sees
void send(String to, String body) {}
}
final class SignupServiceBefore {
private final SmtpMailer mailer = new SmtpMailer(); // hard-wired: no way to substitute
String signup(String email) { mailer.send(email, "welcome"); return email; }
}
// ---------- after: collaborators come in through the constructor ----------
interface Mailer { void send(String to, String body); }
interface UserRepository { boolean exists(String email); void save(String email); }
final class SignupService {
private final UserRepository users;
private final Mailer mailer;
SignupService(UserRepository users, Mailer mailer) {
this.users = Objects.requireNonNull(users);
this.mailer = Objects.requireNonNull(mailer);
}
void signup(String email) {
if (users.exists(email)) throw new IllegalArgumentException("already registered: " + email);
users.save(email);
mailer.send(email, "welcome");
}
}
class ConstructorInjectionDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
try { new SignupServiceBefore(); check(false, "should not construct"); }
catch (IllegalStateException expected) { } // before: untestable without infrastructure
Set<String> stored = new HashSet<>();
List<String> sent = new ArrayList<>();
UserRepository repo = new UserRepository() {
public boolean exists(String e) { return stored.contains(e); }
public void save(String e) { stored.add(e); }
};
SignupService service = new SignupService(repo, (to, body) -> sent.add(to + ":" + body));
service.signup("ana@x.io");
check(stored.contains("ana@x.io") && sent.equals(List.of("ana@x.io:welcome")), "saved and welcomed");
try { service.signup("ana@x.io"); check(false, "duplicate"); }
catch (IllegalArgumentException expected) { }
check(sent.size() == 1, "no second email on duplicate");
System.out.println("tested with no SMTP server and no database");
}
}
from typing import Protocol
# ---------- before: the service builds its own collaborators ----------
class SmtpMailer:
def __init__(self) -> None:
raise RuntimeError("no SMTP server reachable") # what a test sees
class SignupServiceBefore:
def __init__(self) -> None:
self._mailer = SmtpMailer() # hard-wired
# ---------- after: collaborators come in through the constructor ----------
class Mailer(Protocol):
def send(self, to: str, body: str) -> None: ...
class UserRepository(Protocol):
def exists(self, email: str) -> bool: ...
def save(self, email: str) -> None: ...
class SignupService:
def __init__(self, users: UserRepository, mailer: Mailer) -> None:
self._users = users
self._mailer = mailer
def signup(self, email: str) -> None:
if self._users.exists(email):
raise ValueError(f"already registered: {email}")
self._users.save(email)
self._mailer.send(email, "welcome")
class InMemoryUsers:
def __init__(self) -> None:
self.stored: set[str] = set()
def exists(self, email: str) -> bool:
return email in self.stored
def save(self, email: str) -> None:
self.stored.add(email)
class RecordingMailer:
def __init__(self) -> None:
self.sent: list[str] = []
def send(self, to: str, body: str) -> None:
self.sent.append(f"{to}:{body}")
try:
SignupServiceBefore()
raise AssertionError("should not construct")
except RuntimeError:
pass
users, mailer = InMemoryUsers(), RecordingMailer()
service = SignupService(users, mailer)
service.signup("ana@x.io")
assert "ana@x.io" in users.stored and mailer.sent == ["ana@x.io:welcome"]
try:
service.signup("ana@x.io")
raise AssertionError("duplicate accepted")
except ValueError:
pass
assert len(mailer.sent) == 1
print("tested with no SMTP server and no database")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: the service builds its own collaborators ----------
class SmtpMailer {
constructor() { throw new Error("no SMTP server reachable"); } // what a test sees
send(_to: string, _body: string): void {}
}
class SignupServiceBefore {
private readonly mailer = new SmtpMailer(); // hard-wired
signup(email: string): void { this.mailer.send(email, "welcome"); }
}
// ---------- after: collaborators come in through the constructor ----------
interface Mailer { send(to: string, body: string): void }
interface UserRepository { exists(email: string): boolean; save(email: string): void }
class SignupService {
constructor(private readonly users: UserRepository, private readonly mailer: Mailer) {}
signup(email: string): void {
if (this.users.exists(email)) throw new Error(`already registered: ${email}`);
this.users.save(email);
this.mailer.send(email, "welcome");
}
}
let constructed = true;
try { new SignupServiceBefore(); } catch { constructed = false; }
check(!constructed, "before: cannot construct in a test");
const stored = new Set<string>();
const sent: string[] = [];
const service = new SignupService(
{ exists: (e) => stored.has(e), save: (e) => { stored.add(e); } },
{ send: (to, body) => { sent.push(`${to}:${body}`); } },
);
service.signup("ana@x.io");
check(stored.has("ana@x.io") && sent.join() === "ana@x.io:welcome", "saved and welcomed");
let duplicate = false;
try { service.signup("ana@x.io"); } catch { duplicate = true; }
check(duplicate && sent.length === 1, "duplicate rejected, no second email");
console.log("tested with no SMTP server and no database");
3.1 Why constructor injection specifically
There are three places a dependency can come in: the constructor, a setter, or a method parameter. For required collaborators, the constructor wins:
- The object is never half-built. After construction it has everything it needs. With setter injection, someone can call
signup()beforesetMailer(), which is a dynamic connascence of execution order. - Dependencies are visible in one place. Reading the constructor tells you what the class talks to. If the list is long, that's useful feedback about cohesion.
- Fields can be final. Collaborators can't be swapped halfway through the object's life.
- No framework required. Plain constructors work in every language and every test.
Use a method parameter when the collaborator varies per call (a Clock for one calculation, a Writer for one export). Use setter injection almost never: only for optional collaborators with a sensible default.
3.2 The composition root
If every class receives its collaborators, something has to create them. That place is the composition root: usually main(), an application bootstrap, or a DI container's configuration. It's the only place that knows about concrete classes like SmtpMailer and PostgresUserRepository. Everything else depends on interfaces.
In an interview, the composition root is your demo main method or driver. Wiring real implementations there, and fakes in tests, is enough to show you understand DI without bringing in a framework. The DIP page has a fuller example.
4. The hidden inputs: time, randomness and IO
Three inputs sneak into business logic more than any others, because the standard library makes them so easy to reach: now(), random() and the file system. Each makes a function's result depend on something the caller can't see or control.
4.1 Time and randomness
A raffle accepts entries until a closing time, then draws a random winner. The "before" version calls the system clock and creates its own random generator. To test "entries after closing are rejected," you'd have to wait for the real closing time. To test "the winner is one of the entrants and the draw is reproducible," you can't, because the result changes every run.
The fix is to inject both. Java has dedicated types for this: java.time.Clock (with Clock.fixed and Clock.offset for tests) and java.util.random.RandomGenerator. Python and TypeScript commonly use plain functions or a seeded random.Random instance.
import java.time.*;
import java.util.*;
import java.util.random.RandomGenerator;
// ---------- before: reaches for the system clock and its own randomness ----------
final class RaffleBefore {
private final Instant closesAt;
private final List<String> entrants = new ArrayList<>();
RaffleBefore(Instant closesAt) { this.closesAt = closesAt; }
void enter(String name) {
if (Instant.now().isAfter(closesAt)) throw new IllegalStateException("closed");
entrants.add(name);
}
String draw() {
if (Instant.now().isBefore(closesAt)) throw new IllegalStateException("still open");
return entrants.get(new Random().nextInt(entrants.size())); // different every run
}
}
// ---------- after: time and randomness are injected ----------
final class Raffle {
private final Instant closesAt;
private final Clock clock;
private final RandomGenerator random;
private final List<String> entrants = new ArrayList<>();
Raffle(Instant closesAt, Clock clock, RandomGenerator random) {
this.closesAt = closesAt; this.clock = clock; this.random = random;
}
void enter(String name) {
if (clock.instant().isAfter(closesAt)) throw new IllegalStateException("closed");
entrants.add(name);
}
String draw() {
if (clock.instant().isBefore(closesAt)) throw new IllegalStateException("still open");
if (entrants.isEmpty()) throw new IllegalStateException("no entrants");
return entrants.get(random.nextInt(entrants.size()));
}
}
/** A clock the test can move. Clock.fixed is enough when time doesn't need to advance. */
final class ManualClock extends Clock {
private Instant now;
ManualClock(Instant start) { now = start; }
void advance(Duration d) { now = now.plus(d); }
@Override public Instant instant() { return now; }
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
@Override public Clock withZone(ZoneId zone) { return this; }
}
class ClockAndRandomDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
static String run(long seed) {
Instant close = Instant.parse("2026-12-01T18:00:00Z");
ManualClock clock = new ManualClock(close.minus(Duration.ofHours(1)));
Raffle raffle = new Raffle(close, clock, new Random(seed));
for (String n : List.of("ana", "bo", "cy", "dee")) raffle.enter(n);
try { raffle.draw(); check(false, "draw while open"); } catch (IllegalStateException expected) { }
clock.advance(Duration.ofHours(2)); // no sleeping: just move the clock
try { raffle.enter("late"); check(false, "late entry"); } catch (IllegalStateException expected) { }
return raffle.draw();
}
public static void main(String[] args) {
String winner = run(42);
check(List.of("ana", "bo", "cy", "dee").contains(winner), "winner is an entrant");
check(run(42).equals(winner), "same seed, same winner: reproducible");
System.out.println("winner with seed 42: " + winner);
}
}
import random
from datetime import datetime, timedelta, timezone
from typing import Callable
# ---------- before: reaches for the system clock and its own randomness ----------
class RaffleBefore:
def __init__(self, closes_at: datetime) -> None:
self._closes_at = closes_at
self._entrants: list[str] = []
def draw(self) -> str:
if datetime.now(timezone.utc) < self._closes_at:
raise RuntimeError("still open")
return random.choice(self._entrants) # different every run
# ---------- after: time and randomness are injected ----------
class Raffle:
def __init__(self, closes_at: datetime, now: Callable[[], datetime], rng: random.Random) -> None:
self._closes_at, self._now, self._rng = closes_at, now, rng
self._entrants: list[str] = []
def enter(self, name: str) -> None:
if self._now() > self._closes_at:
raise RuntimeError("closed")
self._entrants.append(name)
def draw(self) -> str:
if self._now() < self._closes_at:
raise RuntimeError("still open")
if not self._entrants:
raise RuntimeError("no entrants")
return self._rng.choice(self._entrants)
class ManualClock:
def __init__(self, start: datetime) -> None:
self.now = start
def __call__(self) -> datetime:
return self.now
def advance(self, delta: timedelta) -> None:
self.now += delta
def run(seed: int) -> str:
close = datetime(2026, 12, 1, 18, tzinfo=timezone.utc)
clock = ManualClock(close - timedelta(hours=1))
raffle = Raffle(close, clock, random.Random(seed))
for name in ("ana", "bo", "cy", "dee"):
raffle.enter(name)
try:
raffle.draw()
raise AssertionError("draw while open")
except RuntimeError:
pass
clock.advance(timedelta(hours=2))
try:
raffle.enter("late")
raise AssertionError("late entry accepted")
except RuntimeError:
pass
return raffle.draw()
winner = run(42)
assert winner in {"ana", "bo", "cy", "dee"}
assert run(42) == winner # reproducible
print("winner with seed 42:", winner)
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: reaches for the system clock and its own randomness ----------
class RaffleBefore {
private readonly entrants: string[] = [];
constructor(private readonly closesAt: number) {}
draw(): string {
if (Date.now() < this.closesAt) throw new Error("still open");
return this.entrants[Math.floor(Math.random() * this.entrants.length)]!; // different every run
}
}
// ---------- after: time and randomness are injected ----------
type Now = () => number; // epoch millis
type Rng = () => number; // same contract as Math.random: [0, 1)
class Raffle {
private readonly entrants: string[] = [];
constructor(private readonly closesAt: number, private readonly now: Now = Date.now, private readonly rng: Rng = Math.random) {}
enter(name: string): void {
if (this.now() > this.closesAt) throw new Error("closed");
this.entrants.push(name);
}
draw(): string {
if (this.now() < this.closesAt) throw new Error("still open");
if (this.entrants.length === 0) throw new Error("no entrants");
return this.entrants[Math.floor(this.rng() * this.entrants.length)]!;
}
}
const close = Date.parse("2026-12-01T18:00:00Z");
let t = close - 3_600_000;
const raffle = new Raffle(close, () => t, () => 0.6); // 0.6 * 4 entrants -> index 2
for (const n of ["ana", "bo", "cy", "dee"]) raffle.enter(n);
let refused = false;
try { raffle.draw(); } catch { refused = true; }
check(refused, "no draw while open");
t += 2 * 3_600_000; // move time, don't wait for it
let late = false;
try { raffle.enter("late"); } catch { late = true; }
check(late, "late entry refused");
check(raffle.draw() === "cy", "deterministic winner");
check(new RaffleBefore(Date.now() + 60_000) instanceof RaffleBefore, "before constructs, but can't be tested deterministically");
console.log("winner:", raffle.draw());
Notice the TypeScript version gives the injected functions production defaults (Date.now, Math.random). That keeps call sites simple while leaving a seam for tests. The same trick works in Python with default arguments, and in Java with a second constructor that passes Clock.systemUTC(). Don't overuse it: a default hides the dependency from readers, so keep it for truly ambient things like time and randomness, not for repositories.
Never sleep in a unit test
Thread.sleep(2000) or time.sleep(2) to "let the clock pass the deadline" makes tests slow and flaky. If a test needs time to pass, inject a clock and move it. If code under test sleeps between retries, inject the sleeper too.
4.2 IO
The same reasoning applies to files, the network and standard input. A function that takes a path and opens the file itself can only be tested with real files. A function that takes a reader or an iterable of lines can be tested with a string. The code that turns a path into a reader moves outward to the shell (see section 6).
import java.io.*;
import java.nio.file.*;
import java.util.*;
// ---------- before: opens the file itself ----------
final class ScoreImporterBefore {
static Map<String, Integer> importFile(String path) throws IOException {
Map<String, Integer> scores = new TreeMap<>();
for (String line : Files.readAllLines(Path.of(path))) {
String[] parts = line.split(",");
scores.merge(parts[0].strip(), Integer.parseInt(parts[1].strip()), Integer::sum);
}
return scores;
}
}
// ---------- after: takes a Reader; the caller decides where the text comes from ----------
final class ScoreImporter {
static Map<String, Integer> read(Reader source) throws IOException {
Map<String, Integer> scores = new TreeMap<>();
BufferedReader in = new BufferedReader(source);
String line;
int lineNo = 0;
while ((line = in.readLine()) != null) {
lineNo++;
if (line.isBlank()) continue;
String[] parts = line.split(",");
if (parts.length != 2) throw new IllegalArgumentException("line " + lineNo + ": expected name,score");
scores.merge(parts[0].strip(), Integer.parseInt(parts[1].strip()), Integer::sum);
}
return scores;
}
}
class IoSeamDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) throws IOException {
Path tmp = Files.createTempFile("scores", ".csv"); // the before version needs a real file
Files.writeString(tmp, "ana,3\nbo,5\nana,4\n");
check(ScoreImporterBefore.importFile(tmp.toString()).equals(Map.of("ana", 7, "bo", 5)), "before");
Files.delete(tmp);
check(ScoreImporter.read(new StringReader("ana,3\n\nbo,5\nana,4\n")).equals(Map.of("ana", 7, "bo", 5)), "after");
try { ScoreImporter.read(new StringReader("ana;3\n")); check(false, "bad line"); }
catch (IllegalArgumentException e) { check(e.getMessage().startsWith("line 1"), "says which line"); }
System.out.println("edge cases tested from strings, no temp files");
}
}
import io
import os
import tempfile
from typing import Iterable
# ---------- before: opens the file itself ----------
def import_file(path: str) -> dict[str, int]:
scores: dict[str, int] = {}
with open(path, encoding="utf-8") as f:
for line in f:
name, score = line.split(",")
scores[name.strip()] = scores.get(name.strip(), 0) + int(score)
return scores
# ---------- after: takes any iterable of lines; the caller opens the file ----------
def read_scores(lines: Iterable[str]) -> dict[str, int]:
scores: dict[str, int] = {}
for line_no, line in enumerate(lines, start=1):
if not line.strip():
continue
parts = line.split(",")
if len(parts) != 2:
raise ValueError(f"line {line_no}: expected name,score")
name = parts[0].strip()
scores[name] = scores.get(name, 0) + int(parts[1])
return scores
fd, path = tempfile.mkstemp(suffix=".csv") # the before version needs a real file
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write("ana,3\nbo,5\nana,4\n")
assert import_file(path) == {"ana": 7, "bo": 5}
os.remove(path)
assert read_scores(io.StringIO("ana,3\n\nbo,5\nana,4\n")) == {"ana": 7, "bo": 5}
assert read_scores(["ana,1", "ana,1"]) == {"ana": 2} # a plain list works too
try:
read_scores(["ana;3"])
raise AssertionError("bad line accepted")
except ValueError as e:
assert str(e).startswith("line 1")
print("edge cases tested from strings, no temp files")
import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: opens the file itself ----------
function importFile(path: string): Map<string, number> {
const scores = new Map<string, number>();
for (const line of readFileSync(path, "utf8").split("\n").filter(Boolean)) {
const [name, score] = line.split(",");
scores.set(name!.trim(), (scores.get(name!.trim()) ?? 0) + Number(score));
}
return scores;
}
// ---------- after: takes lines; the caller decides where they come from ----------
function readScores(lines: Iterable<string>): Map<string, number> {
const scores = new Map<string, number>();
let lineNo = 0;
for (const line of lines) {
lineNo++;
if (line.trim() === "") continue;
const parts = line.split(",");
if (parts.length !== 2) throw new Error(`line ${lineNo}: expected name,score`);
const name = parts[0]!.trim();
scores.set(name, (scores.get(name) ?? 0) + Number(parts[1]));
}
return scores;
}
const dir = mkdtempSync(join(tmpdir(), "scores-")); // the before version needs a real file
writeFileSync(join(dir, "s.csv"), "ana,3\nbo,5\nana,4\n");
check(importFile(join(dir, "s.csv")).get("ana") === 7, "before");
rmSync(dir, { recursive: true });
const result = readScores("ana,3\n\nbo,5\nana,4".split("\n"));
check(result.get("ana") === 7 && result.get("bo") === 5, "after");
let message = "";
try { readScores(["ana;3"]); } catch (e) { message = (e as Error).message; }
check(message.startsWith("line 1"), "says which line");
console.log("edge cases tested from strings, no temp files");
The "after" importer also got better error handling, almost by accident. Once testing a malformed line costs one string literal rather than a temp file, you write that test, and then you notice the original crashed with an unhelpful ArrayIndexOutOfBoundsException or ValueError: not enough values to unpack.
5. Test doubles: dummies, stubs, fakes, spies and mocks
Once collaborators are injected, tests pass in test doubles: stand-ins for the real thing. Gerard Meszaros named the kinds in xUnit Test Patterns (2007), and Martin Fowler's essay Mocks Aren't Stubs (2007) popularised the distinctions. People say "mock" for all of them, but the differences matter because each supports a different kind of assertion.
| Double | What it does | You assert on | Example |
|---|---|---|---|
| Dummy | Fills a parameter. Never actually used | Nothing | A null logger, or new NoOpAuditLog() passed to satisfy a constructor |
| Stub | Returns canned answers to calls | The object under test's output or state | An exchange-rate source that always returns 1.10 |
| Fake | A working but simplified implementation | State, through the fake's own API | An in-memory repository backed by a HashMap |
| Spy | Records the calls it receives, for later inspection | What was called, after the fact | A notifier that appends each message to a list |
| Mock | Pre-programmed with expectations and fails if they aren't met | The interaction itself | A mocking library's verify(notifier).send("…") |
There are two broad testing styles, and they lean on different doubles:
- State verification (sometimes called classical or Detroit-school): run the code, then check the resulting state or return value. Uses stubs and fakes. Tests survive refactoring well because they don't care how the result was produced.
- Behaviour verification (mockist or London-school): check that the object under test made the right calls to its collaborators. Uses spies and mocks. Useful when the call is the result, such as sending an email or publishing an event. The risk is tests that break whenever the implementation changes, even if the behaviour didn't.
A good default is to use state verification for queries and fakes for repositories, and use spies or mocks only for outgoing commands whose effect you can't observe any other way, like notifications and payments.
import java.util.*;
interface ExchangeRates { long toCents(String currency, long amountMinor); }
interface OrderRepository { void save(String id, long cents); Optional<Long> find(String id); }
interface Notifier { void send(String message); }
interface AuditLog { void record(String event); }
final class CheckoutService {
private final ExchangeRates rates; private final OrderRepository orders;
private final Notifier notifier; private final AuditLog audit;
CheckoutService(ExchangeRates rates, OrderRepository orders, Notifier notifier, AuditLog audit) {
this.rates = rates; this.orders = orders; this.notifier = notifier; this.audit = audit;
}
long checkout(String id, String currency, long amountMinor) {
long cents = rates.toCents(currency, amountMinor);
orders.save(id, cents);
if (cents >= 100_000) notifier.send("large order " + id);
return cents;
}
}
// Stub: canned answer
final class FixedRates implements ExchangeRates {
public long toCents(String currency, long amountMinor) { return currency.equals("EUR") ? amountMinor * 110 / 100 : amountMinor; }
}
// Fake: a real, simplified implementation
final class InMemoryOrders implements OrderRepository {
private final Map<String, Long> rows = new HashMap<>();
public void save(String id, long cents) { rows.put(id, cents); }
public Optional<Long> find(String id) { return Optional.ofNullable(rows.get(id)); }
}
// Spy: records what it was told
final class SpyNotifier implements Notifier {
final List<String> messages = new ArrayList<>();
public void send(String message) { messages.add(message); }
}
// Dummy: required by the constructor, irrelevant to this test
final class DummyAudit implements AuditLog { public void record(String event) { throw new AssertionError("not expected"); } }
class TestDoublesDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
InMemoryOrders orders = new InMemoryOrders();
SpyNotifier notifier = new SpyNotifier();
CheckoutService service = new CheckoutService(new FixedRates(), orders, notifier, new DummyAudit());
check(service.checkout("o-1", "EUR", 10_000) == 11_000, "state: converted with the stubbed rate");
check(orders.find("o-1").equals(Optional.of(11_000L)), "state: the fake holds the order");
check(notifier.messages.isEmpty(), "behaviour: small order, no notification");
service.checkout("o-2", "USD", 150_000);
check(notifier.messages.equals(List.of("large order o-2")), "behaviour: one notification, right text");
System.out.println("stub, fake, spy and dummy each did one job");
}
}
from typing import Protocol
from unittest.mock import Mock
class ExchangeRates(Protocol):
def to_cents(self, currency: str, amount_minor: int) -> int: ...
class CheckoutService:
def __init__(self, rates, orders, notifier, audit) -> None:
self._rates, self._orders, self._notifier, self._audit = rates, orders, notifier, audit
def checkout(self, order_id: str, currency: str, amount_minor: int) -> int:
cents = self._rates.to_cents(currency, amount_minor)
self._orders.save(order_id, cents)
if cents >= 100_000:
self._notifier.send(f"large order {order_id}")
return cents
class FixedRates: # stub
def to_cents(self, currency: str, amount_minor: int) -> int:
return amount_minor * 110 // 100 if currency == "EUR" else amount_minor
class InMemoryOrders: # fake
def __init__(self) -> None:
self.rows: dict[str, int] = {}
def save(self, order_id: str, cents: int) -> None:
self.rows[order_id] = cents
def find(self, order_id: str) -> int | None:
return self.rows.get(order_id)
class SpyNotifier: # spy
def __init__(self) -> None:
self.messages: list[str] = []
def send(self, message: str) -> None:
self.messages.append(message)
orders, notifier = InMemoryOrders(), SpyNotifier()
service = CheckoutService(FixedRates(), orders, notifier, audit=None) # None is the dummy
assert service.checkout("o-1", "EUR", 10_000) == 11_000
assert orders.find("o-1") == 11_000
assert notifier.messages == []
service.checkout("o-2", "USD", 150_000)
assert notifier.messages == ["large order o-2"]
# The same behaviour check with the standard library's mock: a mock verifies the interaction.
mock_notifier = Mock()
CheckoutService(FixedRates(), InMemoryOrders(), mock_notifier, None).checkout("o-3", "USD", 200_000)
mock_notifier.send.assert_called_once_with("large order o-3")
print("stub, fake, spy, dummy and mock each did one job")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
interface ExchangeRates { toCents(currency: string, amountMinor: number): number }
interface OrderRepository { save(id: string, cents: number): void; find(id: string): number | undefined }
interface Notifier { send(message: string): void }
interface AuditLog { record(event: string): void }
class CheckoutService {
constructor(
private readonly rates: ExchangeRates,
private readonly orders: OrderRepository,
private readonly notifier: Notifier,
private readonly audit: AuditLog,
) {}
checkout(id: string, currency: string, amountMinor: number): number {
const cents = this.rates.toCents(currency, amountMinor);
this.orders.save(id, cents);
if (cents >= 100_000) this.notifier.send(`large order ${id}`);
return cents;
}
}
const fixedRates: ExchangeRates = { // stub
toCents: (c, a) => (c === "EUR" ? Math.floor((a * 110) / 100) : a),
};
class InMemoryOrders implements OrderRepository { // fake
private readonly rows = new Map<string, number>();
save(id: string, cents: number): void { this.rows.set(id, cents); }
find(id: string): number | undefined { return this.rows.get(id); }
}
class SpyNotifier implements Notifier { // spy
readonly messages: string[] = [];
send(message: string): void { this.messages.push(message); }
}
const dummyAudit: AuditLog = { record: () => { throw new Error("not expected"); } }; // dummy
const orders = new InMemoryOrders();
const notifier = new SpyNotifier();
const service = new CheckoutService(fixedRates, orders, notifier, dummyAudit);
check(service.checkout("o-1", "EUR", 10_000) === 11_000, "state: stubbed rate");
check(orders.find("o-1") === 11_000, "state: fake holds the order");
check(notifier.messages.length === 0, "behaviour: no notification");
service.checkout("o-2", "USD", 150_000);
check(notifier.messages.join() === "large order o-2", "behaviour: one notification");
console.log("stub, fake, spy and dummy each did one job");
5.1 Rules of thumb for doubles
- Prefer fakes for things with state (repositories, caches, queues). A fake behaves like the real thing, so tests read like usage, and one fake serves hundreds of tests. Many teams ship an in-memory fake alongside every repository interface.
- Don't mock what you don't own. Mocking a third-party HTTP client ties your tests to your guess about how that library behaves. Wrap it in your own small interface (an Adapter) and double that. Test the adapter separately against the real thing.
- Don't mock values.
Money,EmailandLocalDateare cheap to build. Use real ones. - One mock per test, at most. If a test verifies five interactions, it's testing the implementation, not the behaviour.
- Fakes need their own tests. A fake that disagrees with the real implementation makes tests lie. Run the same contract test suite against both.
6. Functional core, imperative shell
Gary Bernhardt's 2012 talk Boundaries gave a name to a structure that makes most testing problems disappear: functional core, imperative shell.
- The core holds the decisions. It's made of pure functions or immutable objects: values in, values out, no IO, no clock, no randomness. It's where the bugs are, and it's trivially testable with plain values.
- The shell does the IO. It reads inputs (from files, databases, the clock), calls the core, and acts on its decisions (sends emails, writes rows). It has few branches, so it needs few tests, mostly integration tests.
flowchart LR
subgraph shell["Imperative shell — IO, few decisions"]
R["Load loans from repository"]
C["Read the clock"]
S["Send emails, save state"]
end
subgraph core["Functional core — decisions, no IO"]
P["planReminders(loans, today) returns reminders"]
end
R --> P
C --> P
P --> S
The core's output is a description of what to do (a list of reminders, a set of commands) rather than the doing itself. That's what makes it testable: you assert on the description.
Here's a library job that emails overdue borrowers. The "before" version interleaves loading, date arithmetic, decisions and email sending in one loop. The "after" version separates a pure planReminders from a thin job that does the IO.
import java.time.*;
import java.util.*;
import java.util.function.*;
record Loan(String member, String title, LocalDate due, boolean finalNoticeSent) {}
record Reminder(String member, String text, boolean isFinal) {}
// ---------- before: decisions tangled with IO and the system clock ----------
final class ReminderJobBefore {
private final Supplier<List<Loan>> load; private final Consumer<String> email;
ReminderJobBefore(Supplier<List<Loan>> load, Consumer<String> email) { this.load = load; this.email = email; }
void run() {
for (Loan loan : load.get()) {
long late = loan.due().until(LocalDate.now()).getDays(); // hidden input, and wrong past a month
if (late > 14 && !loan.finalNoticeSent()) email.accept(loan.member() + ": final notice");
else if (late > 0) email.accept(loan.member() + ": overdue");
}
}
}
// ---------- after: a pure core ... ----------
final class ReminderPolicy {
private ReminderPolicy() {}
static List<Reminder> plan(List<Loan> loans, LocalDate today) {
List<Reminder> out = new ArrayList<>();
for (Loan loan : loans) {
long late = java.time.temporal.ChronoUnit.DAYS.between(loan.due(), today);
if (late > 14 && !loan.finalNoticeSent()) out.add(new Reminder(loan.member(), loan.title() + " is " + late + " days late: final notice", true));
else if (late > 0 && late <= 14) out.add(new Reminder(loan.member(), loan.title() + " is " + late + " days late", false));
}
return out;
}
}
// ---------- ... and a thin imperative shell ----------
final class ReminderJob {
private final Supplier<List<Loan>> load; private final Consumer<Reminder> send; private final Clock clock;
ReminderJob(Supplier<List<Loan>> load, Consumer<Reminder> send, Clock clock) { this.load = load; this.send = send; this.clock = clock; }
void run() { ReminderPolicy.plan(load.get(), LocalDate.now(clock)).forEach(send); }
}
class FunctionalCoreDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
LocalDate today = LocalDate.of(2026, 11, 10);
List<Loan> loans = List.of(
new Loan("ana", "Dune", today.minusDays(3), false),
new Loan("bo", "Emma", today.minusDays(40), false),
new Loan("cy", "Ulysses", today.plusDays(5), false),
new Loan("dee", "Beloved", today.minusDays(20), true));
// The core is tested with plain values: no doubles, no clock, no email.
List<Reminder> plan = ReminderPolicy.plan(loans, today);
check(plan.size() == 2, "ana overdue, bo final; cy not due; dee already had a final notice");
check(plan.get(1).equals(new Reminder("bo", "Emma is 40 days late: final notice", true)), "bo");
// The shell gets one wiring test.
List<Reminder> sent = new ArrayList<>();
new ReminderJob(() -> loans, sent::add, Clock.fixed(Instant.parse("2026-11-10T09:00:00Z"), ZoneOffset.UTC)).run();
check(sent.equals(plan), "shell sends what the core planned");
// The bug the before version hid: Period.getDays() ignores whole months.
check(today.minusDays(40).until(today).getDays() == 9, "40 days late reads as 9");
System.out.println(plan);
}
}
from dataclasses import dataclass
from datetime import date, timedelta
from typing import Callable, Iterable
@dataclass(frozen=True)
class Loan:
member: str
title: str
due: date
final_notice_sent: bool = False
@dataclass(frozen=True)
class Reminder:
member: str
text: str
is_final: bool
# ---------- before: decisions tangled with IO and the system clock ----------
def run_reminders_before(load: Callable[[], list[Loan]], email: Callable[[str], None]) -> None:
for loan in load():
late = (date.today() - loan.due).days # hidden input
if late > 14 and not loan.final_notice_sent:
email(f"{loan.member}: final notice")
elif late > 0:
email(f"{loan.member}: overdue") # dee gets nagged after her final notice
# ---------- after: a pure core ... ----------
def plan_reminders(loans: Iterable[Loan], today: date) -> list[Reminder]:
out = []
for loan in loans:
late = (today - loan.due).days
if late > 14 and not loan.final_notice_sent:
out.append(Reminder(loan.member, f"{loan.title} is {late} days late: final notice", True))
elif 0 < late <= 14:
out.append(Reminder(loan.member, f"{loan.title} is {late} days late", False))
return out
# ---------- ... and a thin imperative shell ----------
def run_reminders(load: Callable[[], list[Loan]], send: Callable[[Reminder], None],
today: Callable[[], date] = date.today) -> None:
for reminder in plan_reminders(load(), today()):
send(reminder)
today = date(2026, 11, 10)
loans = [
Loan("ana", "Dune", today - timedelta(days=3)),
Loan("bo", "Emma", today - timedelta(days=40)),
Loan("cy", "Ulysses", today + timedelta(days=5)),
Loan("dee", "Beloved", today - timedelta(days=20), final_notice_sent=True),
]
plan = plan_reminders(loans, today) # the core: plain values in and out
assert [r.member for r in plan] == ["ana", "bo"]
assert plan[1] == Reminder("bo", "Emma is 40 days late: final notice", True)
sent: list[Reminder] = []
run_reminders(lambda: loans, sent.append, today=lambda: today) # the shell: one wiring test
assert sent == plan
print(plan)
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
interface Loan { member: string; title: string; dueDay: number; finalNoticeSent: boolean } // dueDay: days since epoch
interface Reminder { member: string; text: string; isFinal: boolean }
const DAY = 86_400_000;
const dayOf = (iso: string): number => Math.floor(Date.parse(iso) / DAY);
// ---------- before: decisions tangled with IO and the system clock ----------
function runRemindersBefore(load: () => Loan[], email: (s: string) => void): void {
for (const loan of load()) {
const late = Math.floor(Date.now() / DAY) - loan.dueDay; // hidden input
if (late > 14 && !loan.finalNoticeSent) email(`${loan.member}: final notice`);
else if (late > 0) email(`${loan.member}: overdue`);
}
}
// ---------- after: a pure core ... ----------
function planReminders(loans: readonly Loan[], today: number): Reminder[] {
const out: Reminder[] = [];
for (const loan of loans) {
const late = today - loan.dueDay;
if (late > 14 && !loan.finalNoticeSent) {
out.push({ member: loan.member, text: `${loan.title} is ${late} days late: final notice`, isFinal: true });
} else if (late > 0 && late <= 14) {
out.push({ member: loan.member, text: `${loan.title} is ${late} days late`, isFinal: false });
}
}
return out;
}
// ---------- ... and a thin imperative shell ----------
function runReminders(load: () => Loan[], send: (r: Reminder) => void, today: () => number): void {
planReminders(load(), today()).forEach(send);
}
const today = dayOf("2026-11-10");
const loans: Loan[] = [
{ member: "ana", title: "Dune", dueDay: today - 3, finalNoticeSent: false },
{ member: "bo", title: "Emma", dueDay: today - 40, finalNoticeSent: false },
{ member: "cy", title: "Ulysses", dueDay: today + 5, finalNoticeSent: false },
{ member: "dee", title: "Beloved", dueDay: today - 20, finalNoticeSent: true },
];
const plan = planReminders(loans, today);
check(plan.map((r) => r.member).join() === "ana,bo", "core decides");
check(plan[1]!.text === "Emma is 40 days late: final notice", "bo's final notice");
const sent: Reminder[] = [];
runReminders(() => loans, (r) => sent.push(r), () => today);
check(JSON.stringify(sent) === JSON.stringify(plan), "shell sends what the core planned");
const nagged: string[] = [];
runRemindersBefore(() => [{ ...loans[3]!, dueDay: Math.floor(Date.now() / DAY) - 20 }], (s) => nagged.push(s));
check(nagged.join() === "dee: overdue", "before: dee nagged after her final notice");
console.log(plan);
Writing the core as a pure function surfaced two bugs in the original. The Java version used Period.getDays(), which returns only the days part of a period, so 40 days late read as 9. And all three "before" versions sent a plain "overdue" email to someone who'd already had their final notice, because the else if caught everything over zero. Both are obvious once the decisions are a function you can call with four sample loans. Both were invisible in a loop that sent real emails.
6.1 In object-oriented designs
"Pure functions" can sound like a functional-programming idea, but it maps naturally onto OO domain models. An entity's methods that change its own state and return events or results, without doing IO, are part of the core. Booking.cancel(now) returning a Refund value is core. The application service that loads the booking, calls cancel, saves it and asks the payment gateway to issue the refund is shell. This is the same split as hexagonal architecture, at class scale.
7. Testing private behaviour through public APIs
A common question: "How do I test this private method?" The usual answer is you don't, directly. You test it through the public methods that use it. Private methods are implementation details. Tests that reach into them break whenever you refactor, which is the opposite of what tests are for.
When that feels inadequate, because the private method holds enough logic that testing it through the public API is awkward, take it as a design signal. The private method wants to be a public method on a different class. Extract it.
import java.util.*;
// ---------- before: a growing private rule, reachable only through signup() ----------
final class AccountsBefore {
private final Set<String> users = new HashSet<>();
void signup(String username, String password) {
if (!isStrong(password, username)) throw new IllegalArgumentException("weak password");
users.add(username);
}
private boolean isStrong(String pw, String username) { // tempting to make public "for tests"
return pw.length() >= 10 && pw.chars().anyMatch(Character::isDigit)
&& !pw.toLowerCase().contains(username.toLowerCase());
}
}
// ---------- after: the rule is a class with its own public API ----------
final class PasswordPolicy {
List<String> violations(String pw, String username) {
List<String> out = new ArrayList<>();
if (pw.length() < 10) out.add("at least 10 characters");
if (pw.chars().noneMatch(Character::isDigit)) out.add("at least one digit");
if (pw.toLowerCase().contains(username.toLowerCase())) out.add("must not contain the username");
return out;
}
}
final class Accounts {
private final PasswordPolicy policy;
private final Set<String> users = new HashSet<>();
Accounts(PasswordPolicy policy) { this.policy = policy; }
void signup(String username, String password) {
List<String> problems = policy.violations(password, username);
if (!problems.isEmpty()) throw new IllegalArgumentException("weak password: " + String.join(", ", problems));
users.add(username);
}
boolean has(String username) { return users.contains(username); }
}
class PrivateBehaviourDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
try { new AccountsBefore().signup("ana", "ana12345678"); check(false, "before"); }
catch (IllegalArgumentException e) { check(e.getMessage().equals("weak password"), "before: which rule failed?"); }
PasswordPolicy policy = new PasswordPolicy(); // each rule tested directly and precisely
check(policy.violations("short1", "ana").equals(List.of("at least 10 characters")), "length");
check(policy.violations("longenough", "ana").equals(List.of("at least one digit")), "digit");
check(policy.violations("ANA-1234567", "ana").equals(List.of("must not contain the username")), "username");
check(policy.violations("correct-horse-9", "ana").isEmpty(), "ok");
Accounts accounts = new Accounts(policy); // and the service through its public API
accounts.signup("ana", "correct-horse-9");
check(accounts.has("ana"), "signed up");
System.out.println("rules tested through a public API, none of them private");
}
}
# ---------- before: a growing private rule, reachable only through signup() ----------
class AccountsBefore:
def __init__(self) -> None:
self._users: set[str] = set()
def signup(self, username: str, password: str) -> None:
if not self._is_strong(password, username):
raise ValueError("weak password")
self._users.add(username)
def _is_strong(self, pw: str, username: str) -> bool: # tests call this "because Python lets them"
return len(pw) >= 10 and any(c.isdigit() for c in pw) and username.lower() not in pw.lower()
# ---------- after: the rule is a class with its own public API ----------
class PasswordPolicy:
def violations(self, pw: str, username: str) -> list[str]:
out = []
if len(pw) < 10:
out.append("at least 10 characters")
if not any(c.isdigit() for c in pw):
out.append("at least one digit")
if username.lower() in pw.lower():
out.append("must not contain the username")
return out
class Accounts:
def __init__(self, policy: PasswordPolicy) -> None:
self._policy = policy
self._users: set[str] = set()
def signup(self, username: str, password: str) -> None:
problems = self._policy.violations(password, username)
if problems:
raise ValueError("weak password: " + ", ".join(problems))
self._users.add(username)
def has(self, username: str) -> bool:
return username in self._users
try:
AccountsBefore().signup("ana", "ana12345678")
raise AssertionError("before accepted")
except ValueError as e:
assert str(e) == "weak password" # which rule failed?
policy = PasswordPolicy()
assert policy.violations("short1", "ana") == ["at least 10 characters"]
assert policy.violations("longenough", "ana") == ["at least one digit"]
assert policy.violations("ANA-1234567", "ana") == ["must not contain the username"]
assert policy.violations("correct-horse-9", "ana") == []
accounts = Accounts(policy)
accounts.signup("ana", "correct-horse-9")
assert accounts.has("ana")
print("rules tested through a public API, none of them private")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: a growing private rule, reachable only through signup() ----------
class AccountsBefore {
private readonly users = new Set<string>();
signup(username: string, password: string): void {
if (!this.isStrong(password, username)) throw new Error("weak password");
this.users.add(username);
}
private isStrong(pw: string, username: string): boolean { // tests cast to any to reach it
return pw.length >= 10 && /\d/.test(pw) && !pw.toLowerCase().includes(username.toLowerCase());
}
}
// ---------- after: the rule is a class with its own public API ----------
class PasswordPolicy {
violations(pw: string, username: string): string[] {
const out: string[] = [];
if (pw.length < 10) out.push("at least 10 characters");
if (!/\d/.test(pw)) out.push("at least one digit");
if (pw.toLowerCase().includes(username.toLowerCase())) out.push("must not contain the username");
return out;
}
}
class Accounts {
private readonly users = new Set<string>();
constructor(private readonly policy: PasswordPolicy) {}
signup(username: string, password: string): void {
const problems = this.policy.violations(password, username);
if (problems.length > 0) throw new Error(`weak password: ${problems.join(", ")}`);
this.users.add(username);
}
has(username: string): boolean { return this.users.has(username); }
}
let beforeMessage = "";
try { new AccountsBefore().signup("ana", "ana12345678"); } catch (e) { beforeMessage = (e as Error).message; }
check(beforeMessage === "weak password", "before: which rule failed?");
const policy = new PasswordPolicy();
check(policy.violations("short1", "ana").join() === "at least 10 characters", "length");
check(policy.violations("longenough", "ana").join() === "at least one digit", "digit");
check(policy.violations("ANA-1234567", "ana").join() === "must not contain the username", "username");
check(policy.violations("correct-horse-9", "ana").length === 0, "ok");
const accounts = new Accounts(policy);
accounts.signup("ana", "correct-horse-9");
check(accounts.has("ana"), "signed up");
console.log("rules tested through a public API, none of them private");
The extracted PasswordPolicy is better design on its own merits, not just for testing. It reports which rules failed, so the sign-up form can show helpful messages. It can be reused for password changes. And it can become an interface later if different tenants need different policies.
7.1 Tempting shortcuts and why to avoid them
| Shortcut | Problem |
|---|---|
Make the method public or package-private "for tests" (Guava's @VisibleForTesting) | Widens the API. Production code starts calling it, and now you can't change it |
| Reflection to call private methods | Tests break on rename. Couples tests to implementation |
obj._private() in Python or (obj as any).secret in TypeScript | Same as reflection, only shorter |
| Asserting on private fields | Tests break when representation changes, even if behaviour didn't |
There's one reasonable exception: legacy code with no tests, where widening visibility is a temporary step on the way to extracting a class. Feathers covers these techniques in detail.
8. What to test in an LLD design
Knowing how to make classes testable still leaves the question of which tests to write, especially in a 90-minute machine-coding round where you might have time for ten. Different kinds of class need different kinds of test, and the design techniques above map onto them neatly.
| Kind of class | What to test | Doubles needed |
|---|---|---|
Value objects (Money, TimeRange, SeatId) | Construction rejects invalid input. Equality and hashing. Arithmetic edge cases such as rounding and overflow | None |
Entities and aggregates (Booking, ParkingSpot, Order) | Every state transition, legal and illegal. Invariants hold after each operation | None, or an injected clock |
Policies and strategies (PricingPolicy, Scheduler) | The decision table: boundaries, ties, empty input | None. They're pure |
Application services (BookingService) | The happy path, each failure path, and what happens to state when a collaborator fails partway through | Fake repository, stub or fake gateway, spy notifier |
Adapters (StripeGateway, CsvLoader) | Translation to and from the external format | The real external thing, in a slower integration test |
A good set of tests for a parking lot, as a concrete example, fits on one screen:
HourlyPricingcharges one hour for a 1-minute stay and two hours for 61 minutes (boundary).HourlyPricingapplies the night rate exactly at the switch-over time (boundary, fixed clock).SpotAllocatorreturns the smallest spot that fits, and nothing when the lot is full.ParkingSpot.occupythrows when the spot is already occupied (illegal transition).ParkingService.exitwith a failing payment gateway leaves the car recorded as parked and the spot occupied (partial failure).ParkingService.exitfor an unknown ticket fails with a clear error (missing reference).- Two vehicles can't be given the same spot (an invariant, and later a concurrency test).
Notice how few doubles that list needs. Items 1 to 4 use real objects and maybe a fixed clock. Only items 5 and 6 need a fake repository and a stub gateway. That ratio is typical of a well-designed system: most of the logic is in the core, which is cheap to test, and the shell is thin.
Also notice that the list is built from the edge cases you clarified at the start of the interview. If you wrote down "61 minutes is two hours" and "the night rate starts at 22:00" during requirements, those become your first tests. The edge-case checklist is a good source.
Tests as a design tool in interviews
Writing one test before the implementation, even as a sketch, forces you to decide the class's public API from the caller's side. "lot.park(car) returns a Ticket, and lot.exit(ticket, card) returns the fee" is a design decision. Making it explicitly, early, tends to produce smaller and clearer interfaces than designing from the inside out.
9. When designing for testability goes too far
David Heinemeier Hansson's 2014 essay Test-induced design damage argued that some teams contort their designs purely to enable isolated unit tests, adding layers and indirection that make the code harder to read. The argument is overstated in places, but the failure modes are real:
| Over-application | Symptom | Better |
|---|---|---|
| An interface for every class | IUserService with one implementation UserService, created only so a mock can be generated | Use interfaces at real boundaries (IO, external services, variation). Test domain classes with real collaborators |
| Mocking everything | Tests for a 10-line method with six mocks and fifteen verify lines | Fakes for stateful collaborators. Real objects for values and domain logic. Mocks only for outgoing commands |
| Tests coupled to implementation | Renaming a private helper breaks twenty tests | Test behaviour through public APIs. Assert on outcomes |
| Injection of ambient values that never vary | A StringFormatter interface injected everywhere | Inject what's non-deterministic or slow (time, randomness, IO, network). Not pure utilities |
| Constructor bloat | Twelve injected collaborators | That's a cohesion problem, not a DI problem. Split the class |
| Layers for isolation's sake | A controller, service, manager and repository each one line deep | Collapse layers that add nothing. Integration tests can cover thin wiring |
A useful rule: inject what's non-deterministic, slow or external; use the real thing for everything else. A Money class, a PasswordPolicy and a SeatMap don't need doubles. A clock, a payment gateway and a database do.
10. How it shows up in LLD interviews
Testability is one of the clearest signals of seniority in an LLD round, and it's cheap to demonstrate.
In whiteboard rounds:
- Say out loud where your seams are: "Pricing depends on a
Clockso we can test peak hours. Payment is behind aPaymentGatewayinterface so we can use a fake in tests." - When asked how you'd test the design, name specific tests: "I'd test
SeatMap.holdfor double-booking and expiry with a fixed clock, and the booking service with an in-memory repository and a spy notifier." - Keep the domain free of IO. If your
ParkingLotclass prints tickets or writes to a database, the interviewer will ask how you'd test it.
In machine-coding rounds (see Machine Coding Rounds):
- Write at least a few tests or a self-checking
main. Interviewers often weigh this heavily. - Inject time and randomness from the start. Retrofitting under time pressure is painful.
- Ship an in-memory repository. It's your storage and your fake.
- Keep your driver (CLI parsing, printing) as the shell, and your domain classes as the core.
Red flags:
LocalDateTime.now(),Math.random()ornew Random()inside domain methods.staticsingletons for repositories or services, so tests can't substitute them. See the untestable statics mistake.- Classes that print instead of returning values.
- "I'd test it manually."
Say this: "I'm injecting the clock and the payment gateway. Everything else in the domain is plain objects, so I can test the rules with real instances and only fake the parts that touch the outside world."
11. Interview questions
-
"What's a seam?" A place where you can change behaviour without editing the code at that place, as Michael Feathers defines it. In OO design it's usually an interface or function parameter whose implementation is chosen elsewhere: real in production, a double in tests.
-
"Why prefer constructor injection over setter injection?" The object is fully initialised after construction, dependencies are visible in one place, fields can be final, and there's no ordering bug where a method runs before a setter. Use setters only for optional collaborators with defaults.
-
"How do you test code that depends on the current time?" Inject a clock:
java.time.Clockin Java, anowfunction in Python or TypeScript. Use a fixed or manually advanced clock in tests. Never sleep. The same goes for randomness: inject a seeded generator or a function. -
"What's the difference between a stub, a fake and a mock?" A stub returns canned answers. A fake is a working simplified implementation, like an in-memory repository. A mock is programmed with expectations and verifies the interactions it receives. Stubs and fakes support state verification, while mocks and spies support behaviour verification.
-
"When should you use mocks?" For outgoing commands whose effect you can't observe any other way, such as sending a notification or charging a card. Avoid them for queries and stateful collaborators, where stubs and fakes give tests that survive refactoring. Don't mock types you don't own. Wrap them in your own interface.
-
"What's 'functional core, imperative shell'?" Put decisions in pure code (values in, values out, no IO), and keep IO in a thin outer layer that gathers inputs, calls the core and executes its decisions. The core gets thorough, fast unit tests. The shell, which has few branches, gets a few integration tests.
-
"How do you test a private method?" Through the public methods that use it. If that's awkward because the private method holds a lot of logic, extract it into its own class with a public API and test that directly. Avoid reflection or widening visibility just for tests.
-
"Isn't adding interfaces for testing over-engineering?" It can be. Add seams for things that are non-deterministic, slow or external: time, randomness, IO, network and third-party services. Domain objects and values should be tested with real instances. An interface per class "for mocking" is test-induced damage.
-
"Your class needs eight constructor parameters to be testable. Is DI the problem?" No. DI made a cohesion problem visible. The class has too many responsibilities, so split it. Some parameters might also belong together in a parameter object or a smaller collaborator.
-
"How would you test a booking service that charges a card and sends an email?" Fake repository for bookings, stub or fake payment gateway that can succeed or fail, spy notifier. Test the happy path, then payment failure (no booking saved, no email), then a duplicate booking. Assert on the repository state and the spy's recorded messages.