Fundamentals 7 min read

Master JUnit5: Why Upgrade from JUnit4 and How to Use Its Powerful Features

This article explains why developers should switch from JUnit4 to JUnit5, outlines the JUnit5 architecture, shows how to add the proper Maven dependency, and provides practical examples of common annotations, assertions, repeated, parameterized, and nested tests for Spring Boot projects.

Programmer DD
Programmer DD
Programmer DD
Master JUnit5: Why Upgrade from JUnit4 and How to Use Its Powerful Features

Why Use JUnit5

JUnit4 is widely used but its syntax can be cumbersome; JUnit5 supports lambda expressions, simpler syntax, and less boilerplate.

JUnit5 is highly extensible and can integrate other test engines.

It offers stronger features such as new assertions, parameterized tests, repeated tests, and more.

Unit testing is essential for developers; systematic tests help during refactoring and ensure new code behaves as expected.

Overview

JUnit5 consists of the following modules:

JUnit Platform – the foundation that allows other test engines to plug in.

JUnit Jupiter – the core engine built on the platform, providing many new features.

JUnit Vintage – a compatibility engine for running JUnit3 and JUnit4 tests on JUnit5.

Dependency Inclusion

When using Spring Boot 2.3.1, add the following dependency and exclude the old JUnit4 engine:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Common Annotations

@BeforeEach – runs before each test method.

@BeforeAll – runs once before all test methods.

@DisplayName – sets a custom name for a test.

@Disabled – disables a test.

@RepeatedTest(n) – repeats a test n times.

@ParameterizedTest – enables parameterized testing.

@ValueSource – provides data for parameterized tests.

Assertions

JUnit Jupiter provides powerful assertion methods in org.junit.jupiter.api.Assertions. Examples include assertTrue, assertFalse, assertNull, assertNotNull, assertThrows, assertTimeout, and assertAll. Sample code:

@Test
@DisplayName("Test assertEquals")
void testEquals() {
    assertTrue(3 < 4);
}

Other assertion examples:

@Test
@DisplayName("Test assertThrows")
void testThrows() {
    ArithmeticException ex = assertThrows(ArithmeticException.class, () -> {
        int m = 5 / 0;
    });
    assertEquals("/ by zero", ex.getMessage());
}
@Test
@DisplayName("Test assertAll")
void testAll() {
    assertAll("Combined assertions",
        () -> assertTrue(1 < 2, "Balance insufficient"),
        () -> assertTrue(3 < 4),
        () -> assertNotNull(new Object())
    );
}

Repeated Tests

Use @RepeatedTest(n) to run a test multiple times, useful for idempotent APIs.

@RepeatedTest(3)
@DisplayName("Repeated test")
void repeatedTest() {
    System.out.println("invoke");
}

Parameterized Tests

Parameterized tests run the same test logic with different inputs using @ParameterizedTest together with @ValueSource.

@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
@DisplayName("Parameterized test")
void paramTest(int a) {
    assertTrue(a > 0 && a < 4);
}

Nested Tests

JUnit5 supports nested test classes to reflect business logic relationships.

@SpringBootTest
@AutoConfigureMockMvc
@DisplayName("JUnit5 unit test")
public class MockTest {
    @Nested
    @DisplayName("Nested order test")
    class OrderTestClass {
        @Test
        @DisplayName("Cancel order")
        void cancelOrder() {
            int status = -1;
            System.out.println("Cancel order successful, status:" + status);
        }
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaunit testingSpring BootassertionsJUnit5
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.