Software Testing & Quality

Unit Testing in Java with JUnit 5 and Mockito 5

Beginner7 min readUpdated

A practical tour of the Java unit-testing toolchain as it stands today: the JUnit Jupiter programming model, AssertJ's fluent assertions, the five kinds of test double and how Mockito implements them. It ends with the harder judgement calls — testing time, testing exceptions, and deciding what should never be mocked.

What you will learn

  • Structure a Jupiter test class with the right lifecycle annotations and a name that states the behaviour
  • Assert with assertAll, assertThrows and AssertJ's fluent API instead of a pile of assertEquals calls
  • Replace repetitive tests with @ParameterizedTest and organise cases with @Nested
  • Tell a dummy, stub, spy, mock and fake apart and pick the cheapest one that works
  • Stub, verify and capture arguments with Mockito 5 without over-specifying the implementation

A unit test is a small, fast, deterministic check on one piece of behaviour, isolated from anything slow enough to notice. It is the only kind of test a developer will happily run dozens of times an hour, which is what makes it the foundation of everything else: refactoring is safe in proportion to how quickly you can find out you broke something.

The Java toolchain for this has been stable for years — JUnit Jupiter for structure, AssertJ for assertions, Mockito for test doubles — but the details have moved. JUnit 5.x and the JUnit 6 line share the Jupiter programming model on Java 17 and later; Mockito 5 uses the inline mock maker by default, so mocking final classes and static methods no longer requires an extra dependency. The examples here assume those versions and a build that puts everything under src/test/java.

What makes a test a unit test

Two properties matter more than any definition of "unit". A unit test must be fast — a suite of a thousand should finish in seconds, so nothing may touch a network, a real database, or the clock in a way that makes it wait. And it must be isolated: running it alone, or in a different order, or in parallel with its neighbours, must give the same result. Shared static state, files written to a fixed path, and a database left dirty by the previous test are the three usual causes when that fails.

Everything else is negotiable. A test that constructs three collaborating value objects is still a unit test in any useful sense. A test that mocks the six dependencies of a service so heavily that it only verifies its own stubs is not a good one, whatever the classification says.

The Jupiter programming model

class InvoiceTotalTest {

    private Invoice invoice;

    @BeforeEach
    void newInvoice() {
        invoice = new Invoice("INV-1", Currency.getInstance("EUR"));
    }

    @Test
    @DisplayName("an empty invoice totals zero in its own currency")
    void emptyInvoiceTotalsZero() {
        assertThat(invoice.total()).isEqualTo(Money.zero("EUR"));
    }

    @Test
    void lineTotalsAreSummed() {
        invoice.add(new Line("Consulting", 3, Money.of("450.00", "EUR")));
        invoice.add(new Line("Licence",    1, Money.of("120.00", "EUR")));

        assertThat(invoice.total()).isEqualTo(Money.of("1470.00", "EUR"));
    }
}

Test classes and methods need no public modifier under Jupiter, and there is no runner: the engine discovers @Test methods directly. @BeforeEach and @AfterEach run around every test; @BeforeAll and @AfterAll run once per class and must be static unless the class is annotated @TestInstance(Lifecycle.PER_CLASS). A new instance of the test class is created for each test method by default, which is what stops one test from leaking state into the next — resist the urge to change that for convenience.

@DisplayName supplies a readable label for reports; @Disabled("reason") skips a test and, unlike commenting it out, leaves a visible trace. @Tag("slow") groups tests so the build can include or exclude them, which is how a single source tree can serve a fast pre-commit run and a fuller pipeline run.

Assertions worth reading

Jupiter's own assertions are adequate and always present. Three are worth knowing even in an AssertJ codebase:

assertAll("customer",
        () -> assertEquals("Ada", customer.firstName()),
        () -> assertEquals("Lovelace", customer.lastName()),
        () -> assertTrue(customer.isActive()));

IllegalStateException thrown = assertThrows(IllegalStateException.class,
        () -> account.withdraw(Money.of("500.00", "EUR")));
assertEquals("INSUFFICIENT_FUNDS", thrown.getErrorCode());

assertTimeoutPreemptively(Duration.ofMillis(200), () -> report.render());

assertAll reports every failure inside it instead of stopping at the first, which turns three re-runs into one. assertThrows returns the caught exception so you can assert on its contents — always prefer a typed error code or a field over matching the message text, since messages get reworded and localised.

AssertJ replaces the guessing game of which assertX to call with a single assertThat and completion:

assertThat(orders)
        .hasSize(3)
        .extracting(Order::status)
        .containsExactly(Status.NEW, Status.PAID, Status.SHIPPED);

assertThat(findCustomer("unknown")).isEmpty();          // Optional

assertThat(response.body())
        .asString()
        .contains("\"currency\":\"EUR\"");

assertThatThrownBy(() -> parser.parse("2026-13-45"))
        .isInstanceOf(DateTimeParseException.class)
        .hasMessageContaining("13");

assertThat(actualOrder)
        .usingRecursiveComparison()
        .ignoringFields("id", "createdAt")
        .isEqualTo(expectedOrder);

usingRecursiveComparison is the answer to the common problem of comparing objects that have no equals worth relying on, and it beats writing a dozen field assertions that will drift out of date. When a domain type is asserted on repeatedly, a custom assertion class extending AbstractAssert gives the suite a vocabulary of its own: assertThat(invoice).isPaid().hasTotalOf("1470.00").

Removing repetition: parameterised and nested tests

When the same behaviour must be checked against several inputs, a parameterised test says so explicitly instead of hiding the cases in a loop:

@ParameterizedTest(name = "IBAN {0} is {1}")
@CsvSource({
        "FR7630006000011234567890189, true",
        "DE89370400440532013000,      true",
        "FR7630006000011234567890188, false",   // wrong check digits
        "XX00,                        false"
})
void validatesIbanCheckDigits(String iban, boolean expected) {
    assertThat(Iban.isValid(iban)).isEqualTo(expected);
}

@ParameterizedTest
@EnumSource(value = Status.class, names = {"SHIPPED", "DELIVERED", "REFUNDED"})
void terminalStatusesCannotBeCancelled(Status status) {
    assertThatThrownBy(() -> new Order(status).cancel())
            .isInstanceOf(IllegalStateException.class);
}

@ParameterizedTest
@MethodSource("discountScenarios")
void appliesTieredDiscount(Money subtotal, Tier tier, Money expected) {
    assertThat(pricing.discount(subtotal, tier)).isEqualTo(expected);
}

static Stream<Arguments> discountScenarios() {
    return Stream.of(
            arguments(Money.of("99.99", "EUR"),  Tier.STANDARD, Money.zero("EUR")),
            arguments(Money.of("100.00", "EUR"), Tier.STANDARD, Money.of("5.00", "EUR")),
            arguments(Money.of("100.00", "EUR"), Tier.PREMIUM,  Money.of("10.00", "EUR")));
}

Each argument set is reported as a separate test, so a failure names the input that broke. The name attribute controls how it appears. Other sources include @ValueSource for a single primitive parameter, @NullAndEmptySource for the two inputs everyone forgets, and @CsvFileSource when the table grows beyond what belongs in an annotation. Boundary values from the test design techniques fit this shape naturally: one row per boundary, with a comment saying which boundary it is.

@Nested inner classes group tests that share a setup and give the report a readable hierarchy:

class ShoppingCartTest {

    @Nested
    class WhenEmpty {
        private final Cart cart = new Cart();

        @Test void totalIsZero()          { assertThat(cart.total()).isZero(); }
        @Test void checkoutIsRejected()   { assertThatThrownBy(cart::checkout).isInstanceOf(EmptyCartException.class); }
    }

    @Nested
    class WithOneItem {
        private final Cart cart = new Cart().add(Item.of("SKU-1", Money.of("20.00", "EUR")));

        @Test void totalIsTheItemPrice()  { assertThat(cart.total()).isEqualTo(Money.of("20.00", "EUR")); }
        @Test void removingLeavesEmpty()  { assertThat(cart.remove("SKU-1").isEmpty()).isTrue(); }
    }
}

Five kinds of test double

"Mock" is used colloquially for all of them, but the distinctions describe real trade-offs.

DoubleWhat it doesTypical use
DummyPassed to satisfy a signature, never usedFilling an unused constructor parameter
StubReturns canned answersFeeding the code under test the data a scenario needs
SpyReal object that records how it was calledLegacy code you cannot easily replace
MockProgrammed with expectations, verified afterwardsChecking that a side effect happened
FakeWorking but simplified implementationIn-memory repository, hash map instead of a cache server

The one people underuse is the fake. An in-memory implementation of a repository interface, written once, makes dozens of tests read like plain code with no stubbing at all, and it catches sequencing bugs that a stub returning a fixed value cannot. If a collaborator interface is small and you keep stubbing it the same way, write the fake.

Mockito in practice

@ExtendWith(MockitoExtension.class)
class SubscriptionServiceTest {

    @Mock  PaymentGateway gateway;
    @Mock  SubscriberRepository subscribers;
    @Mock  Mailer mailer;

    @InjectMocks SubscriptionService service;

    @Test
    void chargesAndActivatesOnSuccess() {
        Subscriber ada = new Subscriber(7L, "[email protected]", Plan.ANNUAL);
        when(subscribers.findById(7L)).thenReturn(Optional.of(ada));
        when(gateway.charge(any(ChargeRequest.class)))
                .thenReturn(ChargeResult.approved("txn-88"));

        service.renew(7L);

        assertThat(ada.status()).isEqualTo(Status.ACTIVE);
        verify(subscribers).save(ada);
        verify(mailer).sendRenewalReceipt("[email protected]", "txn-88");
    }

    @Test
    void doesNotActivateWhenTheCardIsDeclined() {
        when(subscribers.findById(7L)).thenReturn(Optional.of(new Subscriber(7L, "[email protected]", Plan.ANNUAL)));
        when(gateway.charge(any())).thenReturn(ChargeResult.declined("insufficient_funds"));

        assertThatThrownBy(() -> service.renew(7L)).isInstanceOf(PaymentDeclinedException.class);

        verify(subscribers, never()).save(any());
        verifyNoInteractions(mailer);
    }
}

MockitoExtension creates the mocks, injects them and — importantly — enforces strict stubs: a stub that is never used fails the test. That rule catches copy-pasted setup and tests that quietly stopped matching the code. When one stub is genuinely conditional, wrap it with lenient() rather than loosening the whole class.

Argument matchers (any(), eq(), argThat()) must be used for all arguments of a call or none — mixing a raw value with a matcher throws. When you need to inspect what was passed, capture it:

@Captor ArgumentCaptor<ChargeRequest> charge;

@Test
void chargesTheAnnualPriceInTheSubscriberCurrency() {
    // ... arrange and act ...
    verify(gateway).charge(charge.capture());

    assertThat(charge.getValue().amount()).isEqualTo(Money.of("199.00", "EUR"));
    assertThat(charge.getValue().idempotencyKey()).isNotBlank();
}

Other things worth knowing: thenAnswer computes a result from the arguments (when(repo.save(any())).thenAnswer(i -> i.getArgument(0)) is the standard "save returns what it was given"); doThrow(...).when(mock).method() stubs void methods; verify(mock, times(2)), atLeastOnce() and InOrder constrain how often and in what order calls happen; and mockStatic / mockConstruction exist for legacy code but should be treated as a signal that the design needs a seam, not as a routine tool.

Awkward dependencies

Time. Inject a java.time.Clock. Production supplies Clock.systemUTC(), the test supplies Clock.fixed(Instant.parse("2026-03-01T09:00:00Z"), ZoneOffset.UTC), and assertions about expiry, retention or business days become exact instead of approximate.

Randomness and identifiers. Take a Supplier<UUID> or a seeded RandomGenerator as a dependency. A test that asserts an idempotency key "is not blank" is much weaker than one that asserts it equals a known value.

Files. Jupiter's @TempDir parameter or field gives each test a fresh directory that is deleted afterwards, which is simpler and safer than a fixed path under /tmp.

Asynchrony. Never Thread.sleep. Either make the component accept an executor so the test can run tasks synchronously, or poll with Awaitility: await().atMost(TWO_SECONDS).untilAsserted(() -> assertThat(store.count()).isEqualTo(3)).

What not to mock

Do not mock types you do not own — a JDBC driver, an HTTP client library, a message broker client. Their contracts are complex, your stub encodes your beliefs about them, and the test then passes whether or not those beliefs are true. Put a thin interface of your own in front of the library and mock that, or test against the real thing in an integration test.

Do not mock value objects, DTOs, collections or enums. Constructing a real one is cheaper than stubbing and infinitely more readable.

Do not mock the class under test, including with a partial spy that stubs half its own methods. If a method is hard to test because another method of the same class does something expensive, that other method wants to be a separate collaborator.

Finally, do not verify every call. Each verify is an assertion about how the code works, and a suite full of them fails on refactorings that changed nothing observable. Verify the side effects that are the point of the method — the payment charged, the message sent — and let return values carry the rest. Naming helps here too: renewalReceiptIsSentAfterASuccessfulCharge states a behaviour, while testRenew2 states nothing at all. The coding standards guide covers the conventions that keep test code readable alongside production code.

Key takeaways

  • A unit test earns its name by being fast and isolated; everything else about the classification is a naming argument.
  • Jupiter creates a fresh test instance per method, needs no runner or public modifiers, and gives you assertAll, assertThrows and @TempDir out of the box.
  • AssertJ's fluent assertions produce better failure messages and handle collections, optionals and whole-object comparison without helper code.
  • @ParameterizedTest with @CsvSource or @MethodSource turns a table of boundary cases into individually reported tests.
  • Know the five test doubles and reach for a fake when the same stubbing keeps repeating; strict stubs will tell you when a mock has drifted from reality.
  • Inject clocks, random sources and executors rather than mocking statics, and never mock types you do not own or the class under test.

Sources and further reading

Frequently asked questions

Should I use JUnit's built-in assertions or AssertJ?
Either works, but AssertJ scales better. Its fluent API discovers the right assertion through code completion, produces failure messages that describe the difference rather than dumping two objects, and handles collections, optionals, exceptions and recursive comparison without helper methods. JUnit's assertions are fine for simple equality and are always available; most teams standardise on AssertJ and use assertThrows or assertAll from Jupiter alongside it.
When should I use @Mock versus constructing the real object?
Mock a collaborator when it is slow, non-deterministic, has side effects you do not want, or when the point of the test is the interaction with it. Use the real object when it is a value, a simple data structure, or a pure function — mocking those makes the test weaker and couples it to an implementation detail. If mocking something requires more than three stubbed calls, that is usually a sign the design has too many collaborators.
Why does Mockito complain about unnecessary stubbings?
MockitoExtension defaults to strict stubs, which fail a test that stubs a call the code under test never makes. It is a genuinely useful check: an unused stub usually means the test no longer matches the production code, or that the stub was copied from another test. Fix the test rather than switching to lenient mode; if one stub is legitimately conditional, mark just that stub with Mockito.lenient().
How do I unit test code that calls LocalDateTime.now()?
Inject a java.time.Clock and read the time through it. Production code gets Clock.systemDefaultZone() from configuration, tests get Clock.fixed(instant, zone) and become deterministic. The same principle applies to random numbers, UUID generation and the file system: take the source of non-determinism as a constructor parameter instead of calling a static factory, and the test needs no bytecode tricks.