JUnit 5 and Mockito
Lifecycle, parameterised tests, assertions worth reading, mocks versus stubs versus fakes, and the over-mocked test that tests nothing.
JUnit 5 and Mockito are the two libraries every Java test in this course runs on, and both are small enough to learn completely in an afternoon. What takes longer is learning what not to do with them: the test that re-implements the class in when(...) clauses, the @BeforeEach that hides what a test needs, the assertion whose failure message is expected: <true> but was: <false>. This lesson is the API, then the habits.
The lifecycle, and what runs when
JUnit 5 (the Jupiter API) creates a new instance of the test class for every test method. That is the rule that explains the rest: fields are per test, so state cannot leak between them; @BeforeEach runs before each method on that fresh instance; @BeforeAll must be static because it runs before any instance exists.
class OrderServiceTest {
static Clock clock; // shared: one for the class
OrderRepository repo; // fresh per test
OrderService service;
@BeforeAll static void clock() { clock = Clock.fixed(Instant.parse("2026-09-18T00:00:00Z"), ZoneOffset.UTC); }
@BeforeEach void setUp() { repo = new InMemoryOrderRepository(); service = new OrderService(repo, clock); }
@Test
@DisplayName("an order over 5000 paise gets the bulk discount")
void bulkDiscount() {
Order o = service.place(cart(6_000));
assertThat(o.total()).isEqualTo(Money.paise(5_400));
}
}@DisplayName is the sentence a failure prints; write it as the rule being tested, so that a red test reads as a broken requirement rather than a broken method name. @Disabled("reason") needs the reason. @Tag("slow") lets the build run the fast ones first. And @TestInstance(PER_CLASS) exists to change the one-instance-per-test rule, which is the first thing to suspect when tests pass alone and fail together.
Parameterised tests: one rule, many rows
The rule "over 5000 paise gets 10% off" has four interesting inputs — under, at, just over, far over — and four copies of a test are four places for the assertion to drift. One test, four rows:
@ParameterizedTest(name = "{0} paise → {1}")
@CsvSource({
"4999, 4999",
"5000, 5000", // "over", not "at least": the boundary is the whole test
"5001, 4501",
"100000, 90000",
})
void discount(int amount, int expected) {
assertThat(new Discount().apply(amount)).isEqualTo(expected);
}@ValueSource for one argument, @CsvSource for several, @EnumSource for every constant, @MethodSource when the rows need to be built (and then the method returns a Stream<Arguments>). The boundary row is the one that catches the >= bug from the first lesson of this course — which is the point: a parameterised test is where you put the boundaries you thought about.
@Nested groups tests that share a setup into an inner class with its own @BeforeEach, so "when the customer is a student" reads as a heading in the report rather than a prefix on six method names.
Assertions worth reading when they fail
JUnit's own assertEquals(expected, actual) works and is argument-order-sensitive in a way that produces backwards messages. AssertJ's fluent form reads in the order you think, and its failure messages do the diff for you:
assertThat(order.lines()).hasSize(2).extracting(Line::sku).containsExactly("A-1", "B-7");
assertThat(order.total()).isEqualTo(Money.paise(5_400));
assertThatThrownBy(() -> service.place(emptyCart()))
.isInstanceOf(EmptyCartException.class)
.hasMessageContaining("empty");Two habits. One behaviour per test, which usually means one or two assertions: a test with nine assertions stops at the first failure and hides the other eight. And assert on the outcome, not the path: assertThat(repo.findById(id)).isPresent() says the order was saved; verify(repo).save(any()) says a method was called, which is the same fact only until someone refactors.
Mockito: mocks, stubs, spies, and which you meant
A stub answers questions: when(rates.forCurrency("INR")).thenReturn(rate). A mock is a stub that also records calls so you can verify them. A spy wraps a real object and records, calling through unless told otherwise. A fake is a working implementation with a shortcut — the InMemoryOrderRepository above — and it is not a Mockito thing at all, which is why it is often the best of the four.
@ExtendWith(MockitoExtension.class)
class PaymentServiceTest {
@Mock PaymentGateway gateway;
@InjectMocks PaymentService service;
@Test
void chargesOnce() {
when(gateway.charge(any(), any())).thenReturn(new Receipt("r-1"));
service.pay(order);
verify(gateway, times(1)).charge(eq(order.total()), any());
verifyNoMoreInteractions(gateway);
}
}MockitoExtension makes an unused stub a failure (strict stubs), which is the single most useful setting in the library: a when(...) that no test path reaches is either dead or a test that does not do what its name says. ArgumentCaptor reads what was passed when eq(...) cannot express it. doThrow(...).when(mock).method() is the form for void methods. And @InjectMocks is convenient until it silently leaves a field null because the constructor signature changed; a real constructor call in @BeforeEach is one more line and never surprises you.
Over-mocking: the test that tests nothing
The first lesson's testingTheMock passed against a wrong Discount because the mock was the discount. The general form: every collaborator is mocked, every when restates what the code does, and the assertion checks that the code called the mocks — so the test is a second copy of the implementation, and it passes whenever the two copies agree, including when both are wrong.
The rule that prevents it: mock what you do not own or cannot run — the payment gateway, the clock, the mail server — and use the real thing or a fake for what you do own. A service and the repository it calls, tested together with an in-memory fake, is one test that catches the bug in either; the same pair with a mocked repository is two tests that catch nothing between them. If the setup has more when(...) lines than the test has assertions, the mock is doing the work the test was supposed to do.
Under the hood: what @ExtendWith and a mock actually are at runtime
@ExtendWith(MockitoExtension.class) does nothing by itself — it is metadata, the same way an annotation always is until something reads it. Jupiter's engine reads it via reflection when it builds the TestDescriptor for the class, and registers MockitoExtension in a per-test ExtensionRegistry. An extension is any class implementing one or more of Jupiter's SPI interfaces — BeforeEachCallback, AfterEachCallback, ParameterResolver, TestInstancePostProcessor, and others — and the engine calls each registered extension's matching method at the corresponding lifecycle point, in registration order. MockitoExtension implements several: BeforeEachCallback to open a Mockito session and initialise every @Mock field, ParameterResolver so a mock can be a test-method parameter instead of a field, and AfterEachCallback to close the session and report any stub that was set up but never invoked — the strict-stubbing check this lesson relies on. None of that is special JVM behaviour; it is the same reflection-plus-interface-dispatch mechanism @BeforeEach itself runs through, just via a registered extension instead of a method on your own test class.
mock(PaymentGateway.class) does not build a real PaymentGateway. Mockito generates, at runtime, a new class — a subclass of the target (or an implementing class, for an interface) — with every non-final method overridden to route through a MockHandler that records the call and checks a stubbing table before deciding what to return. Two libraries do the actual work: Objenesis instantiates that generated subclass without calling any constructor, using low-level JVM instantiation strategies, which is why a constructor that does real work or throws does not stop a class from being mockable; ByteBuddy generates the subclass's bytecode at runtime. This is Mockito's "subclass" mock maker (the default before Mockito 5), and it is the real, mechanical reason a final method or class historically could not be mocked: a subclass cannot override a final method, and the JVM refuses to let any class extend a final class — Mockito was never choosing not to support it, the bytecode it would need to generate cannot compile. The "inline" mock maker (opt-in before Mockito 5, the default since) instead attaches a java.lang.instrument agent that rewrites the target class's own bytecode in place, which is what makes mocking final classes, final methods and static methods (mockStatic) possible at all, at the cost of needing that instrumentation agent attached.
Try it yourself
Trace what a hand-rolled mock's stub and call log actually store
This mirrors, in miniature, the two pieces of state a real Mockito mock keeps separate: a stubbing table it consults to answer a call, and a call log verify reads afterwards.
class RecordingGateway {
List<Object[]> calls = new ArrayList<>();
Map<Integer, String> stubs = new HashMap<>();
void when(int amount, String receiptId) { stubs.put(amount, receiptId); }
String charge(int amount) {
calls.add(new Object[]{"charge", amount});
String id = stubs.get(amount);
return id == null ? null : "Receipt[" + id + "]";
}
long timesCalled(String method) {
return calls.stream().filter(c -> c[0].equals(method)).count();
}
}
RecordingGateway gateway = new RecordingGateway();
gateway.when(500, "r-1");
String result = gateway.charge(500);
System.out.println("charge(500) -> " + result);
System.out.println("verify calls to charge: " + gateway.timesCalled("charge"));If gateway.charge(500) were called a second time, would the stubbing table "remember" it already answered once and behave differently — or answer the exact same way again?
Why a stub is a rule, not a one-shot queue
It answers the exact same way again, indefinitely. stubs.get(amount) is a rule keyed by input, consulted fresh on every call — it has no memory of how many times it has already fired. That mirrors real Mockito's default: when(...).thenReturn(...) stubs an answer for a matching call, and every matching call gets that same answer, unless you explicitly chain consecutive answers (thenReturn(a, b)) or use thenAnswer for per-call logic. The call log (calls here, what verify reads in real Mockito) is a completely separate, append-only piece of state from the answer table — which is exactly why verify(gateway, times(2)) can tell "answered the same thing twice" apart from "was called once": one question is answered by the stubbing table, the other by the log, and they are never the same data structure.
Misconceptions
- "
@ExtendWith(MockitoExtension.class)is what turns@Mockfields into mocks." Not the annotation directly — see Under the hood above: the annotation only registersMockitoExtensionas an extension; it is theTestInstancePostProcessor/BeforeEachCallbackmethods that extension implements which actually create and inject the mocks. Practically: forget the extension (orMockitoAnnotations.openMocks(this)in the older, non-JUnit-5-native style) and every@Mockfield is silentlynull— the failure shows up as an NPE on first use, not as an error on the annotation itself. - "A
@Spyis a safer mock because it wraps a real object." A spy calls through to the real method unless that specific call is explicitly stubbed, so an un-stubbed call on a spy runs real logic — hits a real database, throws a real exception — inside what looks, from the test's perspective, like an isolated unit test. Stub every method a spy's test path actually reaches, or reach for a real fake instead of a partially-stubbed spy.
Sources
- JUnit 5 User Guide — the extension model chapter (
ExtensionContext,BeforeEachCallback,ParameterResolver). - Mockito documentation — mock makers (the default subclass maker vs. the inline maker) and
MockitoExtension.