Getting Started with JUnit 5

JUnit 5 is a popular framework for unit testing in Java. It introduces powerful new features, improved modularity, and a more flexible API compared to JUnit 4. If you’re just starting out with unit testing or making the switch from JUnit 4 to JUnit 5, this guide will give you a solid foundation.

This tutorial will cover the key differences between JUnit 5 and JUnit 4, annotations like @Test@BeforeEach@AfterEach, and @DisplayName, basic assertions, test structure, and how to set up JUnit 5 with Maven or Gradle.

Table of Contents

  1. What’s New in JUnit 5 Compared to JUnit 4?
  2. JUnit 5 Key Annotations and Test Structure
  3. Basic Assertions in JUnit 5
  4. Setting Up JUnit 5 with Maven or Gradle
  5. Final Thoughts

What’s New in JUnit 5 Compared to JUnit 4?

JUnit 5 introduces several enhancements over JUnit 4. Here’s a quick comparison to help you understand the key differences:

Feature JUnit 4 JUnit 5
Architecture Monolithic framework Modularized into three components (Platform, Jupiter, Vintage)
Annotations Basic annotations for tests. New annotations like @BeforeEach@AfterEach, and @Nested.
Compatibility Supported only in Java 7+ Runs on Java 8+ and introduces better language integration.
Assertions Limited assertion options More expressive and extensive assertion library.
Extension Model Custom rules via @Rule. An extensible, declarative Extension Model, great for adding dynamic test functionality.
Dynamic Tests Not supported Supports dynamic test definitions using @TestFactory.

JUnit 5 is fully modularized. Its main modules include:

  • JUnit Platform for running tests.
  • JUnit Jupiter as the core engine of JUnit 5.
  • JUnit Vintage for backward compatibility with JUnit 3 and 4 tests.

By migrating to JUnit 5, you gain access to a modern, flexible testing framework that is ready for the latest Java features.


JUnit 5 Key Annotations and Test Structure

JUnit 5 simplifies test definitions with its new annotations, making your test cases more expressive and clean. Below are the essential annotations you’ll commonly use.

@Test Annotation

The @Test annotation marks a method as a test case. This is the most basic annotation for defining tests in JUnit 5.

Example:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {

    @Test
    void testAddition() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }
}

Key Differences:

  • JUnit 5 uses org.junit.jupiter.api.Test instead of JUnit 4’s org.junit.Test.
  • No need to declare public methods. JUnit 5 supports package-private access.

@BeforeEach and @AfterEach

  • @BeforeEach runs setup tasks before each test.
  • @AfterEach runs cleanup tasks after each test.

These annotations are helpful for initializing test data, mock objects, or database connections.

Example:

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;

class DatabaseTest {

    Database db;

    @BeforeEach
    void setup() {
        db = new Database();
        db.connect();
        System.out.println("Database connected!");
    }

    @AfterEach
    void cleanup() {
        db.disconnect();
        System.out.println("Database disconnected!");
    }
}

@DisplayName

Use @DisplayName to label tests with more descriptive, human-readable names. This improves readability in test reports.

Example:

import org.junit.jupiter.api.DisplayName;

class UserServiceTest {

    @Test
    @DisplayName("Test user creation")
    void testCreateUser() {
        UserService userService = new UserService();
        User user = userService.createUser("John Doe");
        assertNotNull(user);
    }
}

The test report will display “Test user creation”, making it easier for teams to identify test cases.


Basic Assertions in JUnit 5

Assertions are the core of any test. JUnit 5 enhances assertions with more expressive options, making it easier to validate test results.

Common Assertions

Here are commonly used assertions in JUnit 5:

  • assertEquals(expected, actual) – Validates that two values are equal.
  • assertNotNull(value) – Checks that an object is not null.
  • assertTrue(condition) – Verifies that a condition is true.
  • assertThrows(exception, executable) – Confirms that the code throws the expected exception.

Example:

import static org.junit.jupiter.api.Assertions.*;

class MathTest {

    @Test
    void testDivide() {
        DivisionService divisionService = new DivisionService();
        assertEquals(2, divisionService.divide(10, 5));
        assertThrows(ArithmeticException.class, () -> divisionService.divide(10, 0), "Should throw ArithmeticException on division by zero");
    }
}

Grouping Assertions

JUnit 5 allows you to group multiple assertions using assertAll. This ensures all assertions are executed before failing the test.

Example:

import static org.junit.jupiter.api.Assertions.assertAll;

class CarTest {

    @Test
    void carPropertiesShouldMatch() {
        Car car = new Car("Tesla", "Model S", 2022);

        assertAll(
            () -> assertEquals("Tesla", car.getMake()),
            () -> assertEquals("Model S", car.getModel()),
            () -> assertEquals(2022, car.getYear())
        );
    }
}

Setting Up JUnit 5 with Maven or Gradle

JUnit 5 can be easily integrated into your project using Maven or Gradle.

Setting Up JUnit 5 with Maven

Add the JUnit 5 dependencies to your pom.xml:

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.9.3</version>
        <scope>test</scope>
    </dependency>
</dependencies>

To run JUnit 5 tests, ensure the Surefire Plugin is up-to-date:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0</version>
        </plugin>
    </plugins>
</build>

Run tests with Maven:

mvn test

Setting Up JUnit 5 with Gradle

Include JUnit 5 dependencies in the build.gradle file:

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
}

Gradle automatically detects @Test-annotated methods when running tests:

./gradlew test

Final Thoughts

JUnit 5 empowers developers with a modern, modular, and flexible testing framework. It builds on JUnit 4 with improvements like annotations, enhanced assertions, and dynamic tests, making it perfect for Java developers.

By learning JUnit’s basics, from annotations like @Test to running tests with Maven or Gradle, you can seamlessly integrate unit testing into your Spring Boot or Java projects. Start writing small, focused tests now to ensure high code quality, and as you grow more comfortable, explore advanced JUnit 5 features like parameterized tests and the extension model.

Unit testing isn’t just a best practice; it’s a crucial skill for building reliable software. Happy testing!

Your SEO-friendly article on “Getting Started with JUnit 5” is ready, covering JUnit 5 vs JUnit 4, key annotations, assertions, and setup with Maven or Gradle. Let me know if there’s anything else you’d like to refine or add!

Getting Started with JUnit 5

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top