StackPractices
intermediate By Mathias Paulenko

JUnit 5: Extensions, Parameterized Tests, Dynamic Tests

Practical JUnit 5 guide: extensions, parameterized and dynamic tests, test interfaces, conditional and parallel execution, and JUnit 4 migration.

Topics: testing

Introduction

JUnit 5 fixed an awkward constraint in JUnit 4: a test class could declare exactly one @RunWith, so combining a Spring runner with Mockito or a parameterized runner meant workarounds and fragile rule ordering. On a real codebase — a few hundred test classes, several CI pipelines, tests that should only run in certain environments — that rigidity shows up fast.

JUnit 5 is a rewrite built as a modular platform rather than a single library. It replaces runners and rules with a composable extension model, gives parameterized and dynamic tests first-class support, and runs on any IDE or build tool through the JUnit Platform. This guide covers what matters in production Java codebases: custom extensions, parameterized test patterns, dynamic tests for data-driven scenarios, conditional and parallel execution, build setup, and what changes when migrating from JUnit 4.

If you’re deciding how this fits a broader suite — unit versus integration versus contract tests — the Testing Strategy Guide covers that layer; this page stays at the JUnit 5 API level.

Architecture

JUnit 5 ships as three modules with different jobs:

  • JUnit Platform: the foundation for launching test frameworks on the JVM. It exposes the TestEngine API that IDEs and build tools call — they don’t invoke JUnit directly, they launch engines through the platform.
  • JUnit Jupiter: the programming and extension model — what you use to write tests (@Test, @ExtendWith, @ParameterizedTest). Its engine is the one that executes your tests day to day.
  • JUnit Vintage: a compatibility engine that executes JUnit 3 and 4 tests alongside Jupiter, so a migration can happen incrementally instead of as a big-bang rewrite.

Any framework can implement TestEngine and plug into the platform — which is why a single mvn test or IDE button can run JUnit 4 and JUnit 5 tests in one pass:

JUnit 5 architecture: IDEs and build tools launch test engines through the JUnit Platform; the Jupiter engine runs Jupiter-API tests while the Vintage engine runs legacy JUnit 3 and 4 tests.

The practical consequence: junit-jupiter is your test-scoped dependency, the platform itself arrives transitively, and junit-vintage-engine is only needed while JUnit 4 tests remain.

Lifecycle and Basics

Test lifecycle annotations

JUnit 5 gives every @Test method a fresh instance of the test class by default (PER_METHOD lifecycle). That isolation is deliberate — fields can’t leak state between tests, so execution order doesn’t matter. JUnit doesn’t guarantee method order — by design; if you genuinely need one (rare, usually an integration scenario), declare @TestMethodOrder(OrderAnnotation.class) and mark methods with @Order.

// LifecycleTest.java — JUnit 5 lifecycle
import org.junit.jupiter.api.*;

class LifecycleTest {

    @BeforeAll
    static void setUpAll() {
        // Runs once before all tests in the class
        // Must be static
    }

    @BeforeEach
    void setUp() {
        // Runs before each test
    }

    @Test
    void firstTest() {
        // Test logic here
    }

    @Test
    void secondTest() {
        // Test logic here
    }

    @AfterEach
    void tearDown() {
        // Runs after each test
    }

    @AfterAll
    static void tearDownAll() {
        // Runs once after all tests in the class
        // Must be static
    }
}

When per-method construction is too expensive — a heavy fixture, an in-memory database — switch to @TestInstance(TestInstance.Lifecycle.PER_CLASS). One instance is then shared by all methods, and @BeforeAll/@AfterAll no longer need to be static:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SharedFixtureTest {

    private ExpensiveFixture fixture;

    @BeforeAll
    void loadFixture() {
        // Non-static is allowed under PER_CLASS
        fixture = ExpensiveFixture.load();
    }
}

The trade-off is real: mutable fields now persist between tests, so one test writing to a shared field can break its neighbor. Reset anything mutable in @BeforeEach, or keep the fixture immutable.

Display names and tags

@DisplayName turns report output into readable documentation, and @Tag is how you slice the suite later — run only unit tests locally, add integration and slow on CI. Both come back in the Maven/Gradle setup below.

// TaggedTest.java — Custom display names and tags
import org.junit.jupiter.api.*;

@DisplayName("Order Service Tests")
class OrderServiceTest {

    @Test
    @DisplayName("should calculate total with tax")
    @Tag("unit")
    void testCalculateTotalWithTax() {
        // Test logic
    }

    @Test
    @DisplayName("should reject order with negative quantity")
    @Tag("unit")
    @Tag("validation")
    void testNegativeQuantity() {
        // Test logic
    }

    @Test
    @DisplayName("should persist order to database")
    @Tag("integration")
    @Tag("slow")
    void testOrderPersistence() {
        // Test logic
    }
}

Assertions

assertAll reports every failing check instead of stopping at the first, and the lambda form of assertion messages skips string building entirely when the test passes:

// AssertionsTest.java — JUnit 5 assertions
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class AssertionsTest {

    @Test
    void testBasicAssertions() {
        assertEquals(4, 2 + 2);
        assertNotEquals(5, 2 + 2);
        assertTrue(5 > 3);
        assertFalse(5 < 3);
        assertNull(null);
        assertNotNull(new Object());
    }

    @Test
    void testWithMessage() {
        assertEquals(4, 2 + 2, "2 + 2 should equal 4");
        // Lazy message using lambda (only evaluated on failure)
        assertEquals(4, 2 + 2, () -> "Calculation failed at runtime");
    }

    @Test
    void testGroupedAssertions() {
        // All assertions run even if one fails
        assertAll("user validation",
            () -> assertEquals("Alice", user.getName()),
            () -> assertEquals("alice@example.com", user.getEmail()),
            () -> assertTrue(user.isActive())
        );
    }

    @Test
    void testExceptions() {
        IllegalStateException ex = assertThrows(
            IllegalStateException.class,
            () -> service.processInvalidOrder()
        );
        assertEquals("Order cannot be processed", ex.getMessage());
    }

    @Test
    void testTimeout() {
        assertTimeout(
            java.time.Duration.ofSeconds(2),
            () -> service.fetchData()
        );

        // Preemptive: kills the operation if timeout exceeded
        assertTimeoutPreemptively(
            java.time.Duration.ofMillis(500),
            () -> service.quickLookup()
        );
    }
}

For richer failure output — diffs on strings, recursive object comparison — pair these with AssertJ’s soft assertions; the JUnit5 Soft Assertions with AssertJ recipe covers that setup.

Parameterized Tests

A parameterized test runs once per input row, and JUnit reports each invocation as its own result — one bad row fails one case, not the whole test. The main decision is which source fits the data:

  • @ValueSource — literals only. Best for single-argument probes like “reject blank input”.
  • @CsvSource — readable two- or three-column tables. Watch the edge cases: an unquoted empty cell is null, '' is an empty string, and single quotes let you embed commas in text.
  • @MethodSource — a factory method returning a Stream or List of arguments or objects. Use it when rows are complex (records, builders) or built in code. The factory must be static unless the class uses @TestInstance(PER_CLASS).
  • @EnumSource — every enum constant, with names/mode filters.
  • @NullSource, @EmptySource, @NullAndEmptySource — combine with @ValueSource to probe boundary inputs in one test.
  • @ArgumentsSource — a custom ArgumentsProvider when data comes from a file, a database, or an external service.

Arguments convert implicitly where the mapping is obvious — String to enum constants, ISO strings to LocalDate or Instant, "1" to int. For anything else, register a converter with @ConvertWith, or use @JavaTimeConversionPattern for dates.

Display names matter more than they look: the default ([1] foo, bar) is useless in CI logs. Always set name = "..." — {index}, {0}, {1}, or {argumentsWithNames} interpolates parameters into the report.

Basic parameterized tests

// ParameterizedTest.java — Parameterized tests with various sources
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.*;

@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 5})
void testPositiveNumbers(int number) {
    assertTrue(number > 0);
}

@ParameterizedTest
@ValueSource(strings = {"", "  ", "\t", "\n"})
void testBlankStrings(String input) {
    assertTrue(input.isBlank());
}

@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"  ", "\t"})
void testBlankOrNullStrings(String input) {
    assertTrue(input == null || input.isBlank());
}

CSV source

// CsvSourceTest.java — CSV-based parameterized tests
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

@ParameterizedTest
@CsvSource({
    "1, 1, 2",
    "2, 3, 5",
    "10, 20, 30",
    "-1, 1, 0",
    "0, 0, 0"
})
void testAddition(int a, int b, int expected) {
    assertEquals(expected, calculator.add(a, b));
}

@ParameterizedTest
@CsvSource({
    "Alice, 30, true",
    "Bob, 17, false",
    "Charlie, 18, true",
    "Diana, 16, false"
})
void testAgeValidation(String name, int age, boolean canVote) {
    Person person = new Person(name, age);
    assertEquals(canVote, person.canVote());
}

Method source

// MethodSourceTest.java — Data from methods
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;

static Stream<Arguments> provideTestData() {
    return Stream.of(
        Arguments.of("admin", "ADMIN", true),
        Arguments.of("user", "USER", true),
        Arguments.of("guest", "GUEST", true),
        Arguments.of("admin", "USER", false)
    );
}

@ParameterizedTest
@MethodSource("provideTestData")
void testRoleCheck(String username, String expectedRole, boolean match) {
    User user = userService.findByUsername(username);
    assertEquals(match, user.hasRole(expectedRole));
}

// Using objects directly
record TestCase(String input, String expected, String description) {}

static Stream<TestCase> provideComplexTestData() {
    return Stream.of(
        new TestCase("hello", "HELLO", "lowercase to uppercase"),
        new TestCase("WORLD", "WORLD", "already uppercase"),
        new TestCase("", "", "empty string"),
        new TestCase("123", "123", "numeric string")
    );
}

@ParameterizedTest
@MethodSource("provideComplexTestData")
void testUppercase(TestCase tc) {
    assertEquals(tc.expected(), tc.input().toUpperCase());
}

Custom display names for parameters

// DisplayNameTest.java — Custom parameterized display names
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

@ParameterizedTest(name = "[{index}] {0} + {1} = {2}")
@CsvSource({
    "1, 2, 3",
    "10, 20, 30",
    "100, 200, 300"
})
void testAdditionWithName(int a, int b, int expected) {
    assertEquals(expected, calculator.add(a, b));
}

@ParameterizedTest(name = "{0} should be valid")
@ValueSource(strings = {"user@example.com", "admin@company.org"})
void testValidEmails(String email) {
    assertTrue(validator.isValid(email));
}

Extensions Model

Extensions replace JUnit 4’s @RunWith and @Rule, and two properties matter in practice: they compose — a class can stack several @ExtendWith entries instead of picking a single runner — and they’re ordinary objects you write yourself, implementing only the callback interfaces you need.

Registration works two ways. @ExtendWith(X.class) is declarative — JUnit instantiates the extension, which suits stateless behavior like the retry example below. @RegisterExtension on a field is programmatic — use it when the extension takes configuration or needs per-test-instance state. JUnit invokes the callbacks in registration order, so put ordering-sensitive extensions first.

The callback interfaces you’ll reach for most:

InterfaceRunsTypical use
BeforeAllCallback / BeforeEachCallbackbefore container / each teststart servers, seed shared state
ParameterResolveron parameter lookupinject objects into test methods
ExecutionConditionper test or containerenable/disable by environment
InvocationInterceptoraround the invocationretry, timing, transaction wrap
TestWatcherafter each test outcomelog failures, capture screenshots
AfterTestExecutionCallback / AfterAllCallbackafter test / containerclose resources

Custom extension

// RetryExtension.java — Retry failed tests automatically
import org.junit.jupiter.api.extension.*;
import java.lang.reflect.Method;

public class RetryExtension implements InvocationInterceptor {

    private static final int MAX_RETRIES = 3;

    @Override
    public void interceptTestTemplateMethod(
            Invocation<Void> invocation,
            ReflectiveInvocationContext<Method> invocationContext,
            ExtensionContext extensionContext) throws Throwable {

        Throwable lastError = null;
        for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
            try {
                invocation.proceed();
                return; // Success, no retry needed
            } catch (Throwable t) {
                lastError = t;
                System.out.printf("Attempt %d failed: %s%n", attempt, t.getMessage());
            }
        }
        throw lastError;
    }
}

// Usage
@ExtendWith(RetryExtension.class)
class FlakyServiceTest {

    @Test
    @DisplayName("should connect to external API")
    void testExternalApiConnection() {
        // Retried up to 3 times if it fails
        assertTrue(apiService.connect());
    }
}

Parameter resolver extension

// DatabaseExtension.java — Inject database connections into tests
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.*;

public class DatabaseExtension implements ParameterResolver, AfterTestExecutionCallback {

    private DatabaseConnection connection;

    @Override
    public boolean supportsParameter(ParameterContext parameterContext,
                                     ExtensionContext extensionContext) {
        return parameterContext.getParameter().getType() == DatabaseConnection.class;
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext,
                                   ExtensionContext extensionContext) {
        connection = new DatabaseConnection("jdbc:postgresql://localhost/test");
        connection.connect();
        return connection;
    }

    @Override
    public void afterTestExecution(ExtensionContext context) {
        if (connection != null) {
            connection.close();
        }
    }
}

// Usage
@ExtendWith(DatabaseExtension.class)
class OrderRepositoryTest {

    @Test
    void testFindById(DatabaseConnection db) {
        // db is automatically injected
        OrderRepository repo = new OrderRepository(db);
        Order order = repo.findById(1L);
        assertNotNull(order);
    }
}

The fictional DatabaseConnection above keeps the example focused, but this exact mechanism — a resolver that hands a managed resource to each test — is how Testcontainers injects container data sources. The Java Testcontainers Integration recipe walks through that full setup.

Dynamic Tests

@TestFactory generates tests at runtime: instead of annotated methods, the factory returns a Stream or Collection of DynamicTest objects, each a display name plus an Executable. JUnit reports every generated test individually.

Two constraints to know before reaching for them:

  • Lifecycle callbacks don’t apply per generated test. @BeforeEach and @AfterEach run once around the factory, not once per DynamicTest — put per-case setup inside the executable.
  • The input set is computed at discovery time, which means it can come from a file, a database, or an HTTP call — but if that source is unavailable when the suite is discovered, the whole factory fails or comes back empty.

Reach for dynamic tests when the test matrix isn’t known until runtime; reach for @ParameterizedTest when it’s a fixed table.

Basic dynamic tests

// DynamicTestTest.java — Generate tests at runtime
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;

import java.util.Map;
import java.util.stream.Stream;
import java.util.List;

class DynamicTestTest {

    @TestFactory
    Stream<DynamicTest> testStringOperations() {
        Map<String, String> expected = Map.of(
            "hello", "HELLO",
            "world", "WORLD",
            "java", "JAVA"
        );

        return expected.entrySet().stream()
            .map(e -> dynamicTest(
                "uppercase: " + e.getKey(),
                () -> assertEquals(e.getValue(), e.getKey().toUpperCase())
            ));
    }

    @TestFactory
    List<DynamicTest> testMultipleScenarios() {
        return List.of(
            dynamicTest("add positive numbers",
                () -> assertEquals(5, calculator.add(2, 3))),
            dynamicTest("add negative numbers",
                () -> assertEquals(-5, calculator.add(-2, -3))),
            dynamicTest("add zero",
                () -> assertEquals(5, calculator.add(5, 0)))
        );
    }
}

Data-driven dynamic tests

// DataDrivenTest.java — Dynamic tests from external data
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.DynamicTest.*;
import java.util.stream.Stream;
import java.util.List;

class DataDrivenTest {

    record TestCase(String name, Runnable test) {}

    @TestFactory
    Stream<DynamicTest> testAllValidationRules() {
        List<TestCase> cases = List.of(
            new TestCase("email is required", () -> {
                assertThrows(ValidationException.class,
                    () -> validator.validateEmail(null));
            }),
            new TestCase("email format is checked", () -> {
                assertThrows(ValidationException.class,
                    () -> validator.validateEmail("not-an-email"));
            }),
            new TestCase("valid email passes", () -> {
                assertDoesNotThrow(
                    () -> validator.validateEmail("user@example.com"));
            }),
            new TestCase("email with subdomain passes", () -> {
                assertDoesNotThrow(
                    () -> validator.validateEmail("user@mail.example.com"));
            })
        );

        return cases.stream()
            .map(tc -> dynamicTest(tc.name(), tc.test()));
    }
}

Test Interfaces

Test interfaces with default @Test methods implement the contract-test pattern: the interface declares a behavioral contract, and each implementation supplies the objects to check. The Comparable contract below is the classic example — any class claiming to be Comparable must satisfy all three properties, and StringComparableTest gets them for free by implementing two factory methods.

Interfaces can carry @Test, @BeforeEach, tags, and even @TestInstance(PER_CLASS) — which is the way to get non-static lifecycle methods into an interface contract.

Default methods in test interfaces

// TestInterface.java — Shared test logic via interfaces
import org.junit.jupiter.api.*;

public interface ComparableContract<T extends Comparable<T>> {

    T createSmallerValue();
    T createLargerValue();

    @Test
    @DisplayName("returns positive when comparing smaller to larger")
    default void returnsPositiveWhenSmallerComparedToLarger() {
        T smaller = createSmallerValue();
        T larger = createLargerValue();
        assertTrue(smaller.compareTo(larger) < 0);
    }

    @Test
    @DisplayName("returns negative when comparing larger to smaller")
    default void returnsNegativeWhenLargerComparedToSmaller() {
        T smaller = createSmallerValue();
        T larger = createLargerValue();
        assertTrue(larger.compareTo(smaller) > 0);
    }

    @Test
    @DisplayName("returns zero when comparing to self")
    default void returnsZeroWhenComparedToSelf() {
        T value = createSmallerValue();
        assertEquals(0, value.compareTo(value));
    }
}

// Implementation
class StringComparableTest implements ComparableContract<String> {

    @Override
    public String createSmallerValue() {
        return "apple";
    }

    @Override
    public String createLargerValue() {
        return "banana";
    }
}

Nested Tests

@Nested groups tests into a BDD-style given/when/then tree. Inner classes must be non-static, and lifecycle scoping is what makes nesting useful: an outer @BeforeEach runs before every nested test, so the outer class sets up shared context while each inner level narrows the scenario — valid input, then invalid input, then edge cases.

Readable up to two or three levels; past that, the tree itself becomes the maintenance cost. Flatten rather than nest deeper.

// NestedTest.java — Group related tests in nested classes
import org.junit.jupiter.api.*;

@DisplayName("Order Service")
class OrderServiceTest {

    @Nested
    @DisplayName("when creating an order")
    class WhenCreating {

        @Test
        @DisplayName("should assign a unique ID")
        void shouldAssignId() {
            Order order = service.create(new OrderRequest("item1", 2));
            assertNotNull(order.getId());
        }

        @Test
        @DisplayName("should set status to pending")
        void shouldSetPendingStatus() {
            Order order = service.create(new OrderRequest("item1", 2));
            assertEquals(OrderStatus.PENDING, order.getStatus());
        }

        @Nested
        @DisplayName("with invalid input")
        class WithInvalidInput {

            @Test
            @DisplayName("should reject empty item ID")
            void shouldRejectEmptyItem() {
                assertThrows(ValidationException.class,
                    () -> service.create(new OrderRequest("", 2)));
            }

            @Test
            @DisplayName("should reject negative quantity")
            void shouldRejectNegativeQuantity() {
                assertThrows(ValidationException.class,
                    () -> service.create(new OrderRequest("item1", -1)));
            }
        }
    }

    @Nested
    @DisplayName("when canceling an order")
    class WhenCanceling {

        @Test
        @DisplayName("should set status to canceled")
        void shouldSetCanceledStatus() {
            Order order = service.create(new OrderRequest("item1", 2));
            service.cancel(order.getId());
            assertEquals(OrderStatus.CANCELED, order.getStatus());
        }

        @Test
        @DisplayName("should reject canceling shipped orders")
        void shouldRejectShippedCancellation() {
            Order order = service.create(new OrderRequest("item1", 2));
            service.ship(order.getId());
            assertThrows(IllegalStateException.class,
                () -> service.cancel(order.getId()));
        }
    }
}

Conditional Execution

@Disabled is the blunt option — the test never runs, anywhere. JUnit 5 also ships conditions evaluated per environment, which is what you want for “only on CI”, “not on Windows”, or “needs Java 21”:

AnnotationRuns the test when
@EnabledOnOs / @DisabledOnOsthe OS (and optionally architecture) matches
@EnabledOnJre / @EnabledForJreRangethe running JVM version matches
@EnabledIfSystemPropertya system property matches a regex
@EnabledIfEnvironmentVariablean env variable matches a regex
@Disabled("reason")never — the reason is printed in reports
@EnabledOnOs(OS.LINUX)
@EnabledIfEnvironmentVariable(named = "CI", matches = "true")
@Test
void onlyOnCiLinux() {
    // Runs only on Linux agents with CI=true
}

The old script-based @EnabledIf and @DisabledIf were removed in JUnit 5.7 — use the property/env variants or write a custom condition.

For anything more elaborate, implement ExecutionCondition. The pattern below disables a test unless -Dtest.env=staging is set:

// ConditionalExtension.java — Run tests based on environment
import org.junit.jupiter.api.extension.*;
import java.lang.annotation.*;
import java.util.Optional;

public class EnvironmentCondition implements ExecutionCondition {

    @Override
    public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
        String env = System.getProperty("test.env", "local");

        // Check for @RequiresStaging annotation
        Optional<RequiresStaging> annotation = context.getTestMethod()
            .flatMap(method -> Optional.ofNullable(
                method.getAnnotation(RequiresStaging.class)));

        if (annotation.isPresent() && !"staging".equals(env)) {
            return ConditionEvaluationResult.disabled("Requires staging environment");
        }

        return ConditionEvaluationResult.enabled("Environment check passed");
    }
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(EnvironmentCondition.class)
public @interface RequiresStaging {}

// Usage
class PaymentServiceTest {

    @Test
    @RequiresStaging
    void testRealPaymentGateway() {
        // Only runs when -Dtest.env=staging
    }
}

Note the trick: annotating the custom annotation itself with @ExtendWith turns @RequiresStaging into a self-registering marker — no extra configuration at the call site.

Parallel Execution

Parallel execution is off by default — JUnit assumes tests may share state. Enable it through src/test/resources/junit-platform.properties on the test classpath:

junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.classes.default=concurrent
junit.jupiter.execution.parallel.mode.default=same_thread
junit.jupiter.execution.parallel.config.strategy=dynamic

This configuration runs top-level classes concurrently but keeps methods inside each class sequential — the sweet spot for most suites, since same-class tests often share fixtures. Setting mode.default=concurrent also parallelizes methods; combine that with @ResourceLock("sharedFile") on any test touching a shared resource (files, ports, a database schema) so those tests serialize against each other, and use @Execution(ExecutionMode.SAME_THREAD) to pin a class or method when needed.

Two caveats: static mutable state and shared fixtures break under concurrency, and assertTimeoutPreemptively already runs the executable on a different thread — mixing the two takes care.

Migrating from JUnit 4

The migration path exists because of Vintage: keep junit-vintage-engine on the classpath and old tests keep running while you port class by class. The mapping is mostly mechanical:

JUnit 4JUnit 5
@RunWith(X.class)@ExtendWith(X.class) — stackable
@Rule / @ClassRuleextension implementing the right callback
@Before / @After@BeforeEach / @AfterEach
@BeforeClass / @AfterClass@BeforeAll / @AfterAll
@Ignore@Disabled
@Category@Tag
@Test(expected = E.class)assertThrows(E.class, ...)
@Test(timeout = ms)assertTimeout / assertTimeoutPreemptively
org.junit.Assertorg.junit.jupiter.api.Assertions

Two traps worth knowing: expected= loses the exception, while assertThrows returns it so the message can be asserted; and @BeforeClass allowed static methods only too — the real change is that @BeforeAll still requires static unless you move to the PER_CLASS lifecycle. Once no JUnit 4 tests remain, drop junit-vintage-engine so nothing lands back on the old engine by accident.

Build Configuration

Two version facts save an hour of debugging: maven-surefire-plugin needs at least 2.22.0 to see JUnit Platform tests at all — an older plugin compiles everything and silently runs zero tests, the classic “build green, tests never ran” incident — and importing junit-bom keeps junit-jupiter, -params, and -engine versions aligned without repeating them.

Maven

<!-- pom.xml — JUnit 5 with Maven Surefire -->
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.11.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-params</artifactId>
        <version>5.11.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.3.0</version>
            <configuration>
                <groups>unit</groups>
                <excludedGroups>slow,integration</excludedGroups>
            </configuration>
        </plugin>
    </plugins>
</build>

Gradle

// build.gradle — JUnit 5 with Gradle
dependencies {
    testImplementation platform('org.junit:junit-bom:5.11.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    testImplementation 'org.junit.jupiter:junit-jupiter-params'
}

test {
    useJUnitPlatform()
    filter {
        includeTags 'unit'
        excludeTags 'slow', 'integration'
    }
    testLogging {
        events 'passed', 'skipped', 'failed'
        exceptionFormat 'full'
    }
}

// Separate task for integration tests
task integrationTest(type: Test) {
    useJUnitPlatform()
    filter {
        includeTags 'integration'
    }
}

Every example on this page ships as a runnable Maven project in the companion repository: the test classes above plus the small domain package they exercise, ready for mvn test.

Best Practices

  • Use @DisplayName for readable test names — test reports become documentation
  • Prefer parameterized tests over duplicated test methods
  • Use assertAll for grouped assertions — all checks run even if one fails
  • Use @Tag to classify tests — lets you run selected groups in CI
  • Write custom extensions for cross-cutting test concerns — don’t repeat setup code
  • Use nested tests to structure complex test scenarios — improves readability
  • Use @TestFactory for data-driven tests from external sources
  • Set lazy assertion messages with lambdas — avoids string concatenation on success
  • Use @Nested to share setup within a group of related tests
  • Keep unit tests under 100ms — mock external dependencies

Common Mistakes

  • Using @BeforeAll without static: JUnit 5 requires @BeforeAll methods to be static unless @TestInstance(Lifecycle.PER_CLASS) is used.
  • Not using assertAll: When more than one assertion fails, you only see the first. assertAll reports all failures.
  • Overusing @Disabled: Disabled tests accumulate and become stale. Delete or fix them.
  • Ignoring parameterized test names: Default names are ugly. Use @ParameterizedTest(name = "...") for readable output.
  • Not using tags: Without tags, you can’t selectively run tests in CI vs local development.
  • Expecting lifecycle callbacks inside dynamic tests: @BeforeEach and @AfterEach run once around the @TestFactory, not per generated test — put setup inside each executable.
  • Using assertTimeoutPreemptively with thread-bound state: it runs the executable on a different thread, so anything tied to ThreadLocal — an active transaction, a SecurityContext — isn’t there. Use assertTimeout in that case.
  • Non-static @MethodSource under the default lifecycle: factory methods must be static unless the class opts into PER_CLASS.

See Also

Frequently Asked Questions

What is the difference between JUnit 4 and JUnit 5?

JUnit 5 is a complete rewrite with a modular architecture (Platform, Jupiter, Vintage). It replaces runners/rules with extensions, adds first-class parameterized tests, dynamic tests, nested tests, and better assertion APIs. JUnit 4 tests can still run via the Vintage engine.

Can JUnit 5 run my existing JUnit 4 tests?

Yes — keep junit-vintage-engine on the test classpath and the platform runs both engines in one pass. Remove the dependency once the suite is fully migrated so new tests can't accidentally use the old API.

How do I run JUnit 5 tests in Maven?

Add the junit-jupiter dependency and configure maven-surefire-plugin 3.x — any version from 2.22.0 up detects JUnit Platform tests. Run with mvn test.

How do I enable parallel test execution?

Set junit.jupiter.execution.parallel.enabled=true in junit-platform.properties on the test classpath, then choose modes for classes and methods (concurrent or same_thread). Guard shared resources with @ResourceLock.

What are JUnit 5 extensions?

Extensions are the JUnit 5 replacement for @RunWith and @Rule. You implement whichever callback interface you need — ParameterResolver to inject arguments, InvocationInterceptor to wrap the call, ExecutionCondition to toggle tests on or off — and register it with @ExtendWith, which stacks several on one class.

When should I use @Disabled versus a conditional execution?

@Disabled is a permanent decision — the test never runs and shows as skipped everywhere. Conditions like @EnabledOnOs or a custom ExecutionCondition are evaluated per environment, so the same suite can adapt to CI versus local runs.

How do parameterized tests work in JUnit 5?

Annotate the method with @ParameterizedTest and pick a source (@ValueSource, @CsvSource, @MethodSource, @EnumSource); JUnit runs it once per parameter set and reports each invocation on its own.

What are dynamic tests?

Tests generated at runtime via @TestFactory. Useful for data-driven testing where test cases come from external sources (files, databases, APIs). Each dynamic test has a display name and an executable — but no per-test lifecycle callbacks.