Lesson · Testing
Testing: JUnit 5, doubles and determinism
13 min readTesting
A test is an executable claim about behaviour. This lesson covers the JUnit 5 shape, parameterized tables, test doubles and where to draw them, and the injections that make a failing test reproducible instead of a rumour.
A test is a claim about behaviour
Every change is a small bet that nothing else moved. A test is how you stop taking that bet on faith: it arranges a situation, performs one action, and asserts the outcome. When it fails, the build fails, and the claim that broke is printed with a line number instead of discovered in production a week later.
JUnit 5 is the current line, and its name covers two pieces. The Platform is the engine host: it discovers tests, builds a plan and reports results, and it can run other engines beside Jupiter. Jupiter is the API you write against: @Test, the assertions, parameterized tests and lifecycle annotations. Almost everything below is Jupiter, and it works because the Platform found it.
A test that cannot fail is not protecting anything. Before trusting a test, picture the change that should turn it red, then make sure that change would actually be caught.
The shape of a JUnit 5 test
A test class is ordinary Java with annotations. A method marked @Test takes no parameters, returns void, and fails if an assertion throws. Assertions come from org.junit.jupiter.api.Assertions, and every one of them accepts an optional message that appears first in the failure output.
Name tests the way you would say the behaviour out loud, and let @DisplayName carry the sentence when the method name cannot. totalIncludesShipping compiles; "subtotal 1000 plus shipping 250 is 1250" reads. The report at 2am is the reader, not you.
- One behaviour per test. If the test name needs the word "and", it is two tests, and one of them will fail for the wrong reason.
- Assert with a message on anything non-obvious.
assertEquals(expected, actual, "total must include shipping")saves the reader a walk through four lines of arithmetic. - Prefer the specific assertion:
assertEquals,assertTrue,assertNulldescribe intent; a bareassertTrue(a == b)hides both the expected and the actual value from the failure output.
Once per class, once per test
JUnit 5 defaults to a fresh instance of the test class for every test method, so fields cannot leak state between tests. Shared setup that is genuinely expensive, such as starting a container, goes in @BeforeAll; per-test setup goes in @BeforeEach.
| Annotation | Runs | Instance |
|---|---|---|
| @BeforeAll | once, before the first test | static by default |
| @BeforeEach | before every test method | fresh instance per test |
| @AfterEach | after every test method | same fresh instance |
| @AfterAll | once, after the last test | static by default |
- Per-method instances are the isolation feature. Order stops mattering and a test cannot pass only because the previous test left something behind.
- `@TestInstance(Lifecycle.PER_CLASS)` relaxes that and lets
@BeforeAllbe an instance method. Reach for it when setup is expensive or needs to be non-static, and accept that you now manage shared state by hand. - Cleanup belongs in `@AfterEach` even when the test asserts green, because resources do not care whether the assertion held.
Write setup so that any single test can run alone. If a test only passes as part of a sequence, the suite is hiding a dependency the production code will also have.
The life of one test run
The engine never runs main. It scans the classpath for test classes, builds a plan, then walks the lifecycle annotations in order: class-level setup, then for each test a fresh instance, its @BeforeEach, the body, and its @AfterEach. One failing test does not stop the suite; the engine records the failure with its message and continues.
The report at the end is the point: pass and fail counts, timings, and for every failure the assertion message, the expected and actual values, and the line. That output is the interface between the test and whoever is on call, so an assertion without context costs someone an evening.
Test run · the life of one suite
the plan
instances created: 0the lifecycle
The engine scans the classpath, finds classes that contain test methods, and builds a plan. It never looks for main: discovery is driven by annotations, not by an entry point.
Expected exceptions, without try/catch
When a method is supposed to fail, assert that it fails: assertThrows(SomeException.class, () -> service.order("SKU-9")) fails the test if nothing is thrown, which is exactly the case a try/catch version misses. It also returns the exception, so the message or a field on it can be asserted.
A try { ... fail(); } catch (Exception e) { } is a smell in a test. It swallows the wrong exception type, loses the object, and passes when the body completes normally only because fail() was forgotten. If the exception type is part of the contract, say so with assertThrows; use assertThrowsExactly when catching a subclass should not count.
A test that passes when nothing throws is worse than no test. It converts a promise into a coin flip.
Tables beat loops of asserts
A loop of asserts in one test stops at the first failure, hides which row broke, and cannot report the others. A parameterized test runs the method once per row, reports every failure with its arguments, and keeps the data beside the claim.
@ParameterizedTest with @ValueSource covers one argument of strings or numbers; @CsvSource covers several arguments as comma-separated rows; @MethodSource points at a method that supplies arguments when fixtures get complicated. The parameterized tests live in the junit-jupiter-params artifact, which the aggregate junit-jupiter dependency already includes.
- Use a table when the assertion is identical and only the inputs change. Three happy paths or four boundary cases are one claim, not four.
- Use separate tests when the assertions differ. If each row needs its own expected exception or its own follow-up check, the table is now a disguise.
- Name the cases in the display name with placeholders such as
{0} plus {1} is {2}, so a red row explains itself in the report.
A parameterized row is a test in the report. You get one red line per broken case instead of one broken loop.
Stubs, mocks, fakes, and the boundary rule
A test double replaces a collaborator so the unit under test can run alone. The names describe behaviour, not tools: a stub answers, a mock also records, a fake actually works, and a spy wraps something real.
Mockito is the common library for the first two: mock(Type.class) creates one, when(...).thenReturn(...) stubs it, verify(...) asserts interactions, and ArgumentCaptor grabs the argument a collaborator received so the real assertion can run against it. The rule of thumb that keeps suites honest: mock at the boundary, and fake the inner domain. Mock the payment gateway and the repository; do not mock your own pricing rules, because then you are testing the mocks.
| Double | What it does | Reach for it when |
|---|---|---|
| Stub | returns canned answers | a collaborator's return value is the input to the test |
| Mock | records calls for verify | the interaction itself is the contract, at a boundary |
| Fake | a working lightweight implementation | the real thing is slow or external, but its behaviour matters |
| Spy | the real object plus recording | you need the real behaviour and one observation |
A test is a claim about behaviour; mocks are scaffolding, not evidence. If every collaborator is mocked, the only thing the suite proves is that the mocks were configured.
Deterministic by injection
A test that passes on Tuesday and fails on Friday is not a test, it is a rumour. The usual causes are the inputs below, and each one has a taming injection: replace the source with something the test controls.
- Time: inject
java.time.Clockrather than callingInstant.now()inside the logic, and the test can pin an instant withClock.fixed(...). Do not callInstant.now()in a test and compare against anotherInstant.now()either. clock-and-testability covers the injection pattern in full. - Randomness: seed it.
new Random(42)produces the same sequence on every machine, so a failure is replayable. randomness covers seeded sequences properly; the point here is that an unseeded run turns a test failure into a coin flip. - Files: use
@TempDir, which the Jupiter extension creates and deletes per test, instead of writing into the working directory or a hardcoded path. - Scheduling and waits: poll for the condition with a timeout rather than
Thread.sleep(500), which is simultaneously too slow on fast machines and too short on loaded ones. - The environment: collaborators arrive through constructor parameters. A service that takes its clock, its client and its repository can be handed test doubles; a service that reaches for a singleton or reads a system property cannot be tested without changing the machine.
If a test cannot be replayed, its failure cannot be fixed. Inject the clock, seed the random, and put the test in charge of the input.
Test anatomy · one run, three diagrams
the shape of the run, the cast, and the injections
the lifecycle rail
Discovery
the engine scans and plans
@BeforeAll
once per class
@BeforeEach
fresh instance per test
@Test
arrange, act, assert
@AfterEach
cleanup, then discard
Report
counts, messages, timing
The default lifecycle creates a new instance for every test method, so setup runs per test and fields cannot leak between tests. @BeforeAll is the one station that runs once.
the cast of doubles
Mock at the boundary you do not own; fake the inner domain. A suite of mocks around your own rules tests the mocks.
the determinism map
Each source of nondeterminism is replaced by something the test controls, which is what makes a failure replayable on another machine.
Integration tests against the real dependency
Unit tests stop at the boundary, which is exactly where the interesting failures live: a query that works in one database dialect, a transaction boundary that only matters under load. Testcontainers starts a real dependency, usually a database, in a Docker container for the duration of the test, then throws it away. The JUnit 5 integration manages the lifecycle with @Testcontainers and @Container.
This is the fix for the classic pair of failures: green with H2, red on Postgres. An in-memory stand-in accepts SQL that the real engine rejects, and it does not reproduce locking, sequences or index behaviour. The cost is honest: the test now needs a working container runtime, and it is slower, which is why the fast unit tests still run first and loud. A pooled connection against the container is still a pool, so connection-pools is worth a read before wiring one up.
Test the dialect you ship. A fake that accepts everything is a test of the fake.
Coverage is a signal, not a score
Coverage measures what ran, not what was checked. Line coverage calls a line covered if an assertion happened somewhere in the method; branch coverage notices an untested if and is worth reading instead, but it still cannot tell whether the assertion was meaningful. A void method with no assertion can hit a hundred percent.
Two habits keep the number useful. Read the uncovered lines first, because they usually cluster around error handling and say which failure modes nobody has ever provoked. Then treat the number as a smell detector rather than a target: a gate that fails the build below a threshold is fine, a team grinding to ninety percent is usually writing assertions that cannot fail. Mutation testing, where a tool (PIT for the JVM) flips a condition and asks whether any test goes red, is the sharper instrument: it measures whether the tests can detect change at all.
| Layer | Speed | Verdict |
|---|---|---|
| Unit tests | milliseconds | The base of the shape: most tests, pure logic, no I/O |
| Integration tests | seconds | Fewer, but each one earns its keep at a boundary |
| End-to-end tests | tens of seconds | Precious and brittle: keep the happy paths, nothing else |
Aim the effort where failure is expensive. The pyramid is a shape, the trophy is a shape; both are arguments about proportion, not about banning a layer.
Tests run in the build
None of this matters if the suite is optional. Running tests through the build, so a red test fails the pipeline, is what turns the claims into enforcement: mvn test inside the lifecycle, or gradlew check, which runs the test task plus the other verification tasks. build-tools covers where test goals bind and why an incremental build can skip a task whose inputs have not changed.
One distinction worth keeping straight: the assert keyword is not a test assertion. It is a language feature for invariants, disabled by default at run time unless -ea is passed, and assertions-and-defensive-programming owns both the keyword and the defensive coding that replaces it in production paths. A JUnit assertion always runs and always fails loudly; that is the property tests need.
The suite is only as real as the pipeline that refuses to ship without it. Wire it into the build and stop asking people to remember.
The green suite that proves nothing
Every collaborator is a mock, every mock returns a canned value, and every test ends with verify() calls on the same mock. The suite is green because it is exercising the mocks, and a bug in the logic under test changes nothing about it. Interaction counts are not assertions of correctness, and no amount of coverage closes that gap. Mock at the boundary, fake the inner domain, and make at least one test assert a real outcome.
Interview angles
What is the difference between a stub, a mock and a fake?+
A stub answers with canned values so the code under test can proceed. A mock also records interactions so they can be verified. A fake is a working lightweight implementation, such as an in-memory repository. The rule in practice: fake the inner domain, mock only at a boundary you do not own.
Why does JUnit create a new instance of the test class for each test?+
Isolation. Per-method instances mean fields cannot carry state from one test to the next, so tests cannot depend on execution order. @BeforeEach runs on the fresh instance; @BeforeAll, which runs once, is static unless the class opts into PER_CLASS lifecycle.
Follow-up: When would you switch to PER_CLASS? When the shared setup is expensive or must be an instance method, and you are prepared to manage the shared state that the default lifecycle was protecting you from.
How do you test that a method throws?+
assertThrows(ExceptionType.class, () -> call()) fails if nothing is thrown and returns the exception so the message can be asserted. A try/catch with fail() is the smell: it can pass when the body does not throw, and it usually checks the wrong type.
Common misconception: That a test which passes proves the exception came from the right place. It proves an exception of that type was thrown anywhere inside the lambda, so keep the lambda to the single call being tested.
Why is a flaky test worse than a failing test?+
A failing test names a problem; a flaky one teaches the team to re-run the build, which also hides the real failures that would have appeared that day. Flakes come from uncontrolled inputs, which is why the fixes are injections: a fixed Clock, a seeded Random, @TempDir for files, and polling instead of sleeping.
The injection is also what makes the failure replayable. A seeded random and a pinned clock mean the exact failing run can be reproduced locally, so the investigation starts from evidence instead of from a screenshot of a CI log.