Skip to content
javahacks.dev
JUnit

The JUnit 5 Handbook for Readable Fast Reliable Tests

A working reference to JUnit 5 and the JUnit 6 line: lifecycle, assertions, parameterized tests, extensions and the habits that keep suites fast.

16 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, OpenJDK, Cucumber and GitHub Actions logos.

A test suite is read far more often than it is written, and most unreadable suites share one cause: tests that repeat their setup, assert three unrelated things and fail with a message that says only expected: <true> but was: <false>. JUnit 5 has the tools to prevent all of that, and most projects use about a fifth of them. This handbook covers the parts you will use daily, with the versions pinned in the prose. The code uses JUnit Jupiter 5.13 on JDK 25. JUnit 6 keeps the same org.junit.jupiter.api package, requires Java 17 or newer and unifies the version of its three parts.

The JUnit user guide is the primary reference. For the wider question of what to test at all, read a practical Java testing strategy. This page is about the framework.

Three projects under one name

JUnit 5 is the Platform (launching tests and the engine API that IDEs and build tools call), Jupiter (the annotations and assertions you write) and Vintage (an engine for JUnit 3 and 4). The split is why a build can run old and new tests side by side. JUnit 5 architecture explains how they fit together, and it is where to look when a build tool reports that no tests were found.

A first test, and why the class is package-private

src/test/java/dev/javahacks/MoneyTest.javajava
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

class MoneyTest {

    @Test
    @DisplayName("adding two amounts in the same currency sums the cents")
    void addsSameCurrency() {
        var total = new Money(250, "USD").plus(new Money(150, "USD"));

        assertEquals(400, total.cents());
    }
}

Jupiter does not require public classes or methods. Package-private keeps tests quiet in the IDE's auto-complete and costs nothing. The expected value goes first in assertEquals; reversing the arguments produces a message that blames the wrong side. Setup for a first project, in both Maven and Gradle, is in the JUnit 5 tutorial for beginners.

Lifecycle: a new instance per method

By default JUnit creates a new instance of the test class for every test method. That is why instance fields do not leak between tests, and why @BeforeAll methods must be static. The order is @BeforeAll, then for each test @BeforeEach, the test, @AfterEach, and finally @AfterAll.

java
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ExpensiveFixtureTest {
    // one instance for all methods; @BeforeAll no longer has to be static
}

Switch to PER_CLASS only when a fixture is costly to build and read-only afterwards. It trades isolation for speed, and the trade is yours to make. Test method order is deterministic but intentionally not obvious, so never depend on it. Lifecycle annotations and execution order lists every callback.

Assertions that explain themselves

Prefer the assertion that names what you mean. assertEquals, assertTrue, assertNull, assertIterableEquals and assertThrows all produce better failures than assertTrue(a.equals(b)). Two deserve attention:

java
@Test
void rejectsNegativeAmounts() {
    var error = assertThrows(IllegalArgumentException.class, () -> new Money(-1, "USD"));

    assertEquals("cents must not be negative: -1", error.getMessage());
}

@Test
void exposesAllFields() {
    var money = new Money(250, "usd");

    assertAll("money",
        () -> assertEquals(250, money.cents()),
        () -> assertEquals("USD", money.currency()));
}

assertThrows returns the exception so you can assert on its message. assertAll runs every lambda and reports all failures, which is the difference between fixing a test in one run and fixing it in three. More on both in assertThrows and assertAll and readable assertions. If you prefer fluent assertions, AssertJ works alongside JUnit with no integration code.

Parameterized tests replace copy and paste

java
@ParameterizedTest(name = "{0} cents in {1} formats as {2}")
@CsvSource({
    "100, USD, $1.00",
    "5,   USD, $0.05",
    "1999, EUR, 19.99 EUR"
})
void formatsMoney(long cents, String currency, String expected) {
    assertEquals(expected, new Money(cents, currency).format());
}

Each row appears as its own test with the name you give it. Use @MethodSource when the arguments are objects, and @EnumSource to cover every constant of an enum. Add the junit-jupiter-params dependency; the junit-jupiter aggregate artifact includes it.

Structure with nested classes

@Nested groups tests by the situation they describe, and each nested class can have its own @BeforeEach:

java
class ShoppingCartTest {

    @Nested
    class WhenEmpty {
        @Test
        void totalIsZero() { /* ... */ }
    }

    @Nested
    class WithItems {
        @BeforeEach
        void addItems() { /* ... */ }
    }
}

Nested classes read well in IDE output and Maven reports because the hierarchy becomes the test's name.

Extensions replace runners and rules

An extension hooks into the lifecycle. Register one with @ExtendWith, and combine as many as you need. Frameworks ship their own (MockitoExtension, SpringExtension), and built-in ones cover common needs such as @TempDir for a temporary directory:

java
@Test
void writesReport(@TempDir Path dir) throws IOException {
    Path report = dir.resolve("report.txt");
    Files.writeString(report, "ok");
    assertEquals("ok", Files.readString(report));
}

JUnit deletes the directory when the test ends. For Mockito, @ExtendWith(MockitoExtension.class) enables strict stubs, which is the source of [UnnecessaryStubbingException](/library/unnecessarystubbingexception-fix-mockito-junit-5) when a stub goes unused.

Speed and parallel runs

Create src/test/resources/junit-platform.properties:

properties
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=same_thread
junit.jupiter.execution.parallel.mode.classes.default=concurrent

This runs test classes in parallel while keeping the methods in each class sequential, which is the safest first step. A suite that breaks under parallelism has shared state, usually a static field, a shared file or a fixed port. Fix that rather than turning parallelism off.

When tests do not run

A green build with zero tests executed is a configuration problem, and it usually means the Surefire version predates JUnit Platform support or the wrong engine is on the classpath. JUnit 5 tests not running in Maven Surefire lists the causes, and no runnable methods covers the JUnit 4 message that appears when a class mixes the two APIs.

Set up the build once, correctly

Most "JUnit does not work" reports are build configuration. Import the bill of materials so that the Platform, Jupiter and the launcher stay on matching versions, and keep one version number to update:

XML
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.junit</groupId>
      <artifactId>junit-bom</artifactId>
      <version>5.11.4</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.27.3</version>
    <scope>test</scope>
  </dependency>
</dependencies>

The version numbers above are examples that were current when this page was written, so check the project's release page for the one to use. With Gradle the equivalent is short, and one line is easy to forget on recent Gradle versions:

kotlin
dependencies {
    testImplementation(platform("org.junit:junit-bom:5.11.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

useJUnitPlatform() is what makes Gradle run Jupiter tests, and without it the build is green with zero tests. On Maven, Surefire 3.0.0 or later is needed for the Platform, and an older version is the usual reason a project reports "No tests to run".

The lifecycle, observed

Reading about callback order is less convincing than watching it. This class prints each hook, and running it once teaches the sequence:

java
class LifecycleTest {

    @BeforeAll static void beforeAll() { System.out.println("beforeAll"); }
    @AfterAll  static void afterAll()  { System.out.println("afterAll"); }

    LifecycleTest() { System.out.println("  constructor"); }

    @BeforeEach void beforeEach() { System.out.println("  beforeEach"); }
    @AfterEach  void afterEach()  { System.out.println("  afterEach"); }

    @Test void first()  { System.out.println("    test first"); }
    @Test void second() { System.out.println("    test second"); }
}
Text
beforeAll
  constructor
  beforeEach
    test first
  afterEach
  constructor
  beforeEach
    test second
  afterEach
afterAll

Notice two constructor lines: one instance per test method. The order of first and second can vary, which is by design. Put expensive work in @BeforeAll only when it is read-only afterwards, and put cleanup in @AfterEach so that a failing test still cleans up, because the @AfterEach and @AfterAll methods run even when the test throws.

More assertions, and when a test should not run

Beyond equality, a few assertions pay for themselves. assertInstanceOf checks a type and returns the cast value, which removes a cast and a failure mode:

java
@Test
void parsesAnIntegerLiteral() {
    Node node = parser.parse("42");

    IntLiteral literal = assertInstanceOf(IntLiteral.class, node);
    assertEquals(42, literal.value());
}

assertTimeout fails a test that runs too long, and it runs the code in the calling thread, so it reports the overrun after the code finishes. assertTimeoutPreemptively interrupts it on another thread, which breaks anything that depends on thread-local state, such as a Spring transaction opened by the test. Use the annotation form for a whole test:

java
@Test
@Timeout(value = 2, unit = TimeUnit.SECONDS)
void importsTheSampleFileQuickly() {
    importer.run(Path.of("src/test/resources/sample.csv"));
}

Assumptions abort a test as skipped, not failed, when a precondition does not hold. Use them for the environment, never to hide a failure:

java
@Test
void readsFromTheSocket() {
    assumeTrue(System.getenv("CI") == null, "needs a local network");
    // ...
}

Annotations do the same for common conditions, and they show up in the report as skipped with their reason:

java
@Test @EnabledOnOs(OS.LINUX)
void usesProcFilesystem() { /* ... */ }

@Test @EnabledIfEnvironmentVariable(named = "DB_URL", matches = ".+")
void talksToTheConfiguredDatabase() { /* ... */ }

@Test @EnabledForJreRange(min = JRE.JAVA_21)
void usesVirtualThreads() { /* ... */ }

@Test @Disabled("flaky since the move to the new queue, tracked in SHOP-412")
void deliversInOrder() { /* ... */ }

A @Disabled without a reason and an issue number is a deletion in slow motion. Make the reason mandatory in review.

Parameterized tests beyond the basics

The earlier example used a CSV string. Real suites need more sources. @MethodSource provides objects, with names for the report:

java
static Stream<Arguments> discounts() {
    return Stream.of(
        Arguments.of("standard, small order", new Order(Tier.STANDARD, 1), new BigDecimal("0.00")),
        Arguments.of("standard, bulk order", new Order(Tier.STANDARD, 10), new BigDecimal("0.10")),
        Arguments.of("gold, bulk order", new Order(Tier.GOLD, 10), new BigDecimal("0.15")));
}

@ParameterizedTest(name = "{0}")
@MethodSource("discounts")
void computesDiscount(String label, Order order, BigDecimal expected) {
    assertEquals(0, expected.compareTo(policy.discountFor(order)));
}

For a large table, keep it in a file next to the tests, where a product owner can review it without reading Java:

java
@ParameterizedTest
@CsvFileSource(resources = "/tax-rates.csv", numLinesToSkip = 1)
void appliesTaxRate(String country, String category, BigDecimal rate) {
    assertEquals(0, rate.compareTo(taxes.rateFor(country, category)));
}

@EnumSource covers every constant and can exclude some, which turns "every status has a label" into one test:

java
@ParameterizedTest
@EnumSource(value = OrderStatus.class, mode = EnumSource.Mode.EXCLUDE, names = "UNKNOWN")
void everyStatusHasADisplayLabel(OrderStatus status) {
    assertFalse(labels.labelFor(status).isBlank());
}

When a test reads a value in a format JUnit cannot convert, write a converter once and apply it with @ConvertWith, instead of parsing strings at the top of every test. The tradeoff to remember is that a parameterized test hides one test method behind many runs, so keep the logic in the body trivial. If the body needs an if per case, the cases are different tests.

Tests that are generated, repeated or ordered

@RepeatedTest runs a test several times, which is useful for a flaky-by-nature concurrency check. @TestFactory builds tests at runtime from data, and each dynamic test is reported separately:

java
@TestFactory
Stream<DynamicTest> everyFixtureFileParses() throws IOException {
    try (Stream<Path> files = Files.list(Path.of("src/test/resources/fixtures"))) {
        return files.sorted()
            .map(file -> DynamicTest.dynamicTest(file.getFileName().toString(),
                () -> assertDoesNotThrow(() -> parser.parse(Files.readString(file)))))
            .toList().stream();
    }
}

Adding a fixture file adds a test with no code change. Ordering is the feature to use with the most care. Tests should not depend on each other, and the exception is a scripted scenario against real infrastructure, where steps share state by design:

java
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class OrderLifecycleIT {

    @Test @Order(1) void createsAnOrder()   { /* ... */ }
    @Test @Order(2) void paysTheOrder()     { /* ... */ }
    @Test @Order(3) void shipsTheOrder()    { /* ... */ }
}

If you find yourself reaching for @Order in a unit test, the test is hiding a missing fixture. Use it for end-to-end flows, and label the class so that nobody copies the pattern.

Readable names without writing them twice

A @DisplayName on every method is accurate and tedious. Generate names from method names instead, and keep descriptive method names:

java
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class MoneyTest {

    @Test
    void adding_amounts_in_different_currencies_is_rejected() {
        assertThrows(CurrencyMismatch.class, () -> new Money(1, "USD").plus(new Money(1, "EUR")));
    }
}

The report shows "adding amounts in different currencies is rejected". Set a project-wide default in junit-platform.properties with junit.jupiter.displayname.generator.default, and reserve @DisplayName for the rare test that needs punctuation or an issue number in the title.

Write your own extension

An extension is a class implementing callback interfaces, and writing one is the right answer when three test classes share setup that is not just a method. This extension measures each test and prints the slow ones, and shows the store, the parameter resolver and the registration:

java
public class SlowTestExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {

    private static final Namespace NS = Namespace.create(SlowTestExtension.class);
    private static final long THRESHOLD_MS = 500;

    @Override
    public void beforeEach(ExtensionContext context) {
        context.getStore(NS).put("start", System.nanoTime());
    }

    @Override
    public void afterEach(ExtensionContext context) {
        long start = context.getStore(NS).remove("start", long.class);
        long ms = (System.nanoTime() - start) / 1_000_000;
        if (ms > THRESHOLD_MS) {
            System.out.printf("SLOW %s took %d ms%n", context.getDisplayName(), ms);
        }
    }

    @Override
    public boolean supportsParameter(ParameterContext p, ExtensionContext c) {
        return p.getParameter().getType() == Clock.class;
    }

    @Override
    public Object resolveParameter(ParameterContext p, ExtensionContext c) {
        return Clock.fixed(Instant.parse("2026-03-14T10:00:00Z"), ZoneOffset.UTC);
    }
}
java
@ExtendWith(SlowTestExtension.class)
class PricingTest {

    @Test
    void usesTheClockItIsGiven(Clock clock) {
        assertEquals(Instant.parse("2026-03-14T10:00:00Z"), clock.instant());
    }
}

The second capability, injecting a Clock into a test method, replaces a base class with a protected field. For an extension that needs configuration, register it as a field with @RegisterExtension, which lets you pass constructor arguments. To apply an extension to every test in a project, list it in META-INF/services/org.junit.jupiter.api.extension.Extension and set junit.jupiter.extensions.autodetection.enabled=true, though explicit registration is easier to follow when something goes wrong.

Tags, filters and the stages of a build

Not every test belongs in every run. Tag the slow ones and select by tag in the build:

java
@Tag("integration")
class OrderRepositoryIT { /* ... */ }
XML
<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <excludedGroups>integration</excludedGroups>
  </configuration>
</plugin>
Shell
./mvnw test                              # fast stage, integration excluded
./mvnw verify -Dgroups=integration       # integration stage

With Gradle, useJUnitPlatform { includeTags("integration") } in a second Test task does the same. A tag is cheaper than a naming convention because it can be combined (@Tag("slow") @Tag("db")) and it survives renames. The mechanics, and how to fold several annotations into one, are in JUnit tags and filters.

Parallel execution that stays correct

The configuration shown earlier runs classes in parallel. Fine-grained control comes from annotations on the classes that need it, which is how a suite stays fast without becoming flaky:

java
@Execution(ExecutionMode.SAME_THREAD)
@ResourceLock(value = "system-properties", mode = ResourceAccessMode.READ_WRITE)
class ConfigurationLoaderTest {

    @Test
    void readsFromSystemProperty() {
        System.setProperty("app.mode", "test");
        // ...
    }
}

@ResourceLock says that tests using the named resource must not run at the same time as others that write it, and JUnit schedules around it. Global state, such as system properties, the default locale and time zone, static singletons and files at fixed paths, is the cause of nearly every parallel failure. Run a suite a few times with parallelism on in CI before you trust it, and when one test fails only in parallel, look for the shared thing before adding a lock. The best fix is no shared state, and the lock is the fix for the state you cannot remove.

Mockito with JUnit 5

Mockito integrates through its own extension, and strict stubs are on by default, which is a feature. An unused stub means the test and the code disagree:

java
@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {

    @Mock PaymentGateway gateway;
    @Mock InventoryClient inventory;
    @InjectMocks CheckoutService service;

    @Test
    void chargesOnceAndReservesStock() {
        when(gateway.charge(any())).thenReturn(Receipt.ok("r-1"));

        Receipt receipt = service.checkout(aCart());

        assertEquals("r-1", receipt.reference());
        verify(inventory).reserve("sku-1", 2);
    }
}

Verify the interactions that are the point of the test, such as the stock reservation above, and not every call. A suite that verifies each collaborator call is a copy of the implementation, and breaks when someone improves it. The distinctions are in what to mock and what to leave real.

Moving from JUnit 4

Migration is mostly mechanical, and a table covers the vocabulary:

JUnit 4JUnit 5
@Before, @After@BeforeEach, @AfterEach
@BeforeClass, @AfterClass@BeforeAll, @AfterAll
@Ignore@Disabled
@Category@Tag
@RunWith, @Rule, @ClassRule@ExtendWith, @RegisterExtension
@Test(expected = ...)assertThrows
@Test(timeout = ...)@Timeout
org.junit.Assertorg.junit.jupiter.api.Assertions

Keep the Vintage engine on the classpath while old and new tests coexist, convert one package at a time, and remove Vintage when the last JUnit 4 import is gone. Run the whole suite after each package, because a @Rule with side effects, such as a temporary folder or an expected-exception rule, behaves differently from its extension equivalent. The JUnit 6 line keeps the programming model described here, with a newer Java baseline, so the habits carry over. Check its release notes for the exact requirements before you upgrade.

Failures and where to look

SymptomLikely causeFirst move
Build is green, zero tests ranOld Surefire, missing useJUnitPlatform() or only Vintage presentCheck the plugin version and the engine on the classpath
@BeforeAll method must be staticDefault per-method lifecycleMake it static, or use PER_CLASS
Test passes alone, fails in the suiteShared static state or leaked fixtureReset in @AfterEach, or remove the sharing
Fails only in parallelGlobal stateFind it, then @ResourceLock or @Execution(SAME_THREAD)
UnnecessaryStubbingExceptionA stub nobody calledDelete the stub or fix the code path
Parameterized test shows one caseName pattern collapsed or one argumentAdd name = "{0}" and inspect the arguments
Tag filter selects nothingTypo in the tag or wrong plugin parameterCompare the tag string and run with -X

Most suites become trustworthy through a handful of habits: independent tests, small fixtures, names that state the behavior, and a decision to fix or delete every test that fails for no reason. The framework supports all four, and the discipline is the part you provide.

How to review a test

A test is code that other people must maintain, and review is where its quality is set. Ask five questions of every test in a pull request. What behavior does it protect, and could it be stated in one sentence? If the production code were deleted, would this test fail, and with a message that says why? Does it depend on anything it does not create, such as a record in a shared database, a file in the home directory or the order of another test? Is the setup visible in the test, or hidden in a base class four levels up? And does it assert on a result, or on how the result was obtained?

Tests that fail these questions share a few shapes, and naming them helps a team spot them early. The first is the test that cannot fail, usually because the assertion is inside a callback that never runs, or because it asserts that a mock returns what it was told to return. The second is the test that restates the code: it computes the expected value with the same formula as the production method, so a wrong formula passes. The third is the oversized test, with a dozen assertions across unrelated behavior, whose name is testProcess and whose failure tells nobody anything. The fourth is the test with time in it, which uses Thread.sleep or the system clock and passes on a fast machine. The fifth is the test that needs a particular machine: a hard-coded path, a locale, a time zone or a port. Each of them has a plain remedy in the sections above, and a review that names the shape and points at the remedy teaches faster than a comment that says "please improve".

Habits that keep a suite healthy

Keep tests close to the code they cover, in the same package, so they can use package-private members without opening the production API. Name the class after what it tests, and keep one behavior per method. Use literal expected values, calculated by hand or taken from a specification, rather than values computed from the code under test. Prefer real objects to mocks for anything cheap and deterministic, and use a mock for the boundary you do not own. Run the whole suite before every push, and treat a slow or flaky test as a defect with an owner, not as weather. When a test is deleted because the behavior is gone, say so in the commit message, and when a bug is fixed, the first commit is the failing test.

Finally, remember what the framework cannot supply. JUnit gives you a place to write the test and a runner to execute it, and a good suite is the result of what you choose to test. The strategy of which tests to write, where, and against what, is the subject of a practical Java testing strategy, and the two pages are meant to be read together.

Where JUnit is the wrong tool

JUnit runs tests; it does not decide which ones to write. A suite of fast, isolated unit tests will not catch a wrong SQL query or a broken serialization format, which need integration tests against real components. It is also not a benchmarking tool: use JMH for timing. And if you keep JUnit 4 tests you cannot migrate yet, keep the Vintage engine on the classpath and move test classes across one at a time. The Jupiter API documentation documents the behavior in detail.

Also inTesting
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.