Workbench / Volume 3 Companion: The Backend
V3·54
Backend Testing
Companion to Volume 3, chapter 54: how strategy, the unit level, the integration level and the system level of testing connect; new angles (a smoke detector you never pressed the test button on, a fire drill for every door, a coin you flip twenty times); what the chapter simplifies, measured on TiffinBox's own suite in stage 55: a mutation run whose every mutant was "killed" by a missing file, 18 of 38 changes to the access rules that 78 passing tests didn't notice, a route that told anonymous callers what was wrong with their request before asking who they were, and what twenty runs of the suite say about flakiness; the theory behind them (controls, mutation score, rules as tests, flakiness as a rate); how Spring's test context cache evicts, from its source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 54 covers strategy (what tests are for, the shape of a suite, test doubles), the unit level (JUnit, AssertJ and Mockito, property-based testing, mutation testing), the integration level (Spring test slices and context caching, repositories with a real database, Testcontainers, API tests, WireMock, contract and architecture tests) and the system level (end-to-end, performance and flaky tests), with testing across languages and a checklist for a Spring service.
The links worth remembering:
- A test's value is the changes it notices. Coverage says a line ran; mutation testing says whether a test would have failed had the line been wrong.
- Rules that apply to everything are tested over everything. "Every route checks access" is a loop over routes, not a test per route someone remembered to write.
- Determinism is a design property. Clocks, randomness, ordering and timing are inputs; a test that doesn't control them measures luck.
Explain it differently
1. A smoke detector you never tested. It's been silent for years: maybe there was no fire, maybe the battery's dead. Press the button first. A mutation run, or any test of tests, needs a control that shows it can tell the difference (Gaps 1).
2. A fire drill for every door. Checking that the front door locks doesn't tell you about the side door someone added last year. Walk every door, every time, and make adding a door mean adding it to the walk (Gaps 3).
3. A coin flipped twenty times. One pass doesn't prove a test is reliable, any more than one heads proves a coin is fair. Flakiness is a rate, measured by repetition (Gaps 4).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 and the build's stage 54 and 55 code (exp/55), unless stated.
1. A test of your tests needs a control. TiffinBox has no build tool that runs PIT, so stage 55 mutates by hand: one change per mutant (== to !=, && to ||, an ALLOW turned into a denial, a negation dropped), compiled over a copy of the server's classes, and the whole server suite run against it. The first run, on the access rules and the token verifier:
Access.java: 38 mutants, 38 killed, 0 survived (100% killed); 7 didn't compile
Tokens.java: 9 mutants, 9 killed, 0 survived (100% killed); 19 didn't compile
Perfect, and meaningless: the tests ran from the repository's root instead of server/, couldn't find the contract file, and failed whether or not anything was mutated. The script now runs the unmutated classes first and stops if they fail. A mutation score, a coverage figure, a "zero flaky tests" dashboard: each is only as good as the evidence that it can come out differently.
2. Passing tests aren't the same as tested rules. With the control in place:
control (no mutation): tests: 78 passed, 0 failed
Access.java: 38 mutants, 20 killed, 18 survived (53% killed); 7 didn't compile
line 49: Decision s = signedIn(c); if (!s.allowed()) return s; -> Decision s = signedIn(c); if (s.allowed()) return s;
line 67: if (kitchenOf(c, o.get()) && !event.equals("refund-paid")) return Decision.ALLOW; -> if (kitchenOf(c, o.get()) || !event.equals("refund-paid")) …
line 76: if (c.who().is(Tokens.Role.ADMIN) || c.who().is(Tokens.Role.KITCHEN) && c.who().subject().equals(kitchen)) … -> … || c.who().is(Tokens.Role.KITCHEN) || c. …
…
Tokens.java: 9 mutants, 7 killed, 2 survived (78% killed); 19 didn't compile
line 86: … || now.getEpochSecond() >= exp) throw new Invalid("expired"); -> … || now.getEpochSecond() > exp) …
Eighteen ways to break TiffinBox's access rules that 78 passing tests (including stage 51's IDOR test and the contract tests) didn't notice: anyone signed in, kitchens included, placing orders as any customer (line 49), anyone signed in moving any order's state except refunds (line 67), any kitchen opening any kitchen's screen (line 76). The tests that existed checked the cases someone thought of during stage 51; the rules had more branches than that. Stage 55 adds AccessTest, a matrix of who × what × whose with one expected status per row, and two token tests (expiry at exactly exp; the key file's current and its keys):
control (no mutation): tests: 88 passed, 0 failed
Access.java: 38 mutants, 38 killed, 0 survived (100% killed); 7 didn't compile
Tokens.java: 9 mutants, 9 killed, 0 survived (100% killed); 19 didn't compile
3. A rule over every route, as a test. Stage 51 put access checks in each route by hand. Stage 55 gives every route a written access description and adds RoutesTest: a route without a sample path in the test fails it (so new routes can't be forgotten), the public routes must be exactly the listed ones, and every other route, called anonymously with access enforced, must answer 401. It found one:
FAIL everyRouteThatIsntPublicRefusesAnAnonymousCaller(): org.opentest4j.AssertionFailedError: POST /orders/(.+)/events (the order's kitchen, its customer (cancel), admin) answered 400 to nobody ==> expected: <401> but was: <400>
The kitchen-event route parsed the body before asking who was calling, so an anonymous caller got a detailed list of what was wrong with its JSON: validation as an oracle for someone who isn't allowed to use the endpoint. Authentication now comes first. The route-by-route tests stage 51 wrote couldn't have found it, because none sent a bad body without credentials.
4. Flakiness is a rate. Stage 53's release check failed once on stage 52's usage test (a count read a few milliseconds before the second request's access line was written) and passed every other time; the fix was a 200 ms sleep, itself a smell. Twenty runs of the whole server suite, as built:
20 runs of the server suite in 297 s; tests that failed at least once:
1 FAIL ordersPlacedAndMovedAtOnceStayConsistent
Stage 39's concurrency test, which never failed alone (60 runs in a row), failed once in 20 runs of the whole suite: it slept 300 ms for a kitchen display to receive the last events, and under the other tests' load the stream was sometimes slower. It now waits until the display has seen every order's final state, up to 10 seconds. (exp/55/repeat-after.out: 20 more runs, no failures, which says the rate is lower, not that it is zero.)
One pass of a suite is one sample. A test that fails 1 time in 50 makes a 10-test-per-hour pipeline red several times a day, and teaches everyone to press "retry". Count failures per test over repeated runs (nightly, or on every merge with retries recorded), and fix or quarantine by rate.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "100% of mutants killed: great tests." | Or a suite that always fails; check the control. | Gaps 1 |
| "Every path has a test." | Every path someone remembered; mutation finds the rest. | Gaps 2 |
| "Each route has its own security test." | A loop over all routes catches the one nobody wrote. | Gaps 3 |
| "It passed, so it's not flaky." | Flakiness is a failure rate; one run can't show it. | Gaps 4 |
| "High coverage means well tested." | Lines ran; nothing says a wrong line would fail a test. | The chapter's lab, Experiment 1 |
Theoretical gaps: the ideas behind the chapter
1. Controls. Any measurement of tests (coverage, mutation, flake detection) needs a case where the answer is known: the unmutated code passes, a known-bad mutant fails, a deliberately flaky test is detected. Without one, a broken harness looks like success.
2. Mutation score as a gap list. The score matters less than the survivors: each is a concrete behaviour no test pins down. Some are equivalent mutants (a change that can't alter behaviour) and should be ignored; the rest are missing tests, usually in boundary conditions (> against >=) and boolean logic (&& against ||).
3. Rules as tests over a set. Properties of the whole system ("every route checks access", "every response has a cache policy", "every change publishes an event") are tested by enumerating the set (routes, responses, operation sequences) and checking each member, with the enumeration failing when the set grows without the test knowing. Stage 55's property test does it for operation sequences (200 random sequences of 60 placements and events: every snapshot equals its kitchen's open orders, and every change moves its kitchen's version); it found nothing, which, after the mutation run, is worth knowing rather than assuming.
4. Flakiness as a rate, determinism as design. Most flakiness comes from uncontrolled inputs: time (stage 55's TestClock), randomness (seeds printed on failure), ordering (tests sharing state), and timing (waiting for something to happen instead of being told it did). Replace sleeps with signals where the code allows it.
Applying it
Code walkthrough
Gaps 4's cost side: a Spring integration test is slow mainly because it starts an application context, so Spring caches contexts between test classes. From spring-projects/spring-framework, main at commit 7ce40c8 (18 November 2026).
The test context cache is an LRU cache
spring-test/src/main/java/org/springframework/test/context/cache/DefaultContextCache.java:
private final Map<MergedContextConfiguration, ApplicationContext> contextMap =
Collections.synchronizedMap(new LinkedHashMap<>(32, 0.75f, true));
...
private void evictLruContextIfNecessary() {
if (this.contextMap.size() >= this.maxSize) {
Iterator<MergedContextConfiguration> iterator = this.contextMap.keySet().iterator();
Assert.state(iterator.hasNext(), "Failed to retrieve LRU context");
// The least recently used (LRU) key is the first/head in a LinkedHashMap
// configured for access-order iteration order.
MergedContextConfiguration lruKey = iterator.next();
remove(lruKey, HierarchyMode.CURRENT_LEVEL);
}
}
And in ContextCache:
int DEFAULT_MAX_CONTEXT_CACHE_SIZE = 32;
...
String MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME = "spring.test.context.cache.maxSize";
The key is the merged configuration: classes, profiles, properties, active @MockitoBeans and more. Every distinct combination is a new context, started from scratch; past 32 of them, the least recently used is closed and must be started again if a later class needs it. This is chapter 53's LRU cache, with a context as the value and seconds as the miss penalty: a suite whose classes each add one @MockitoBean or one property gets a hit rate near zero. Fewer, shared configurations (a few base classes) are the fix; the cache's logging (org.springframework.test.context.cache at DEBUG) prints its statistics.
Debugging drills
D1. A perfect score
A team reports 100% mutation coverage on a new module, after adding mutation testing to CI last week.
D2. The rule everyone thought was tested
After an incident (a user reached data they shouldn't), the team finds tests for that endpoint that pass, written by the person who wrote the rule.
D3. A new endpoint, unprotected
A new admin endpoint shipped without an access check; every existing security test passed.
D4. Green on retry
A pipeline is "usually green": about one run in five fails, and passes when rerun.
Career-oriented
Interview prep
Mid-level 1: mock or fake
Question. "When would you use a fake instead of a mock?"
How to get there. What does each test verify?
Mid-level 2: testing time
Question. "How do you test code that depends on the current time?"
How to get there. Make time an input.
Senior 1: a suite people trust
Question. "Developers rerun failed builds without reading them. What do you do?"
How to get there. Find out why failures aren't believed.
Senior 2: how good are our tests?
Question. "Coverage is 85%. Are our tests good?"
How to get there. What would show whether the tests notice wrong code?
Staff 1: system-wide rules
Question. "How would you make sure every service follows rules like 'every endpoint is authenticated' and 'every response sets a cache policy'?"
How to get there. Turn each rule into something that runs over the whole set.
Staff 2: the test pyramid in practice
Question. "Our suite takes 40 minutes. Design a faster one without losing confidence."
How to get there. Find where the time goes, then move checks to the cheapest level that can catch each bug.