Automated Testing with JUnit 5 Maven Setup: A Comprehensive Guide

Automated Testing with JUnit 5 Maven Setup: A Comprehensive Guide

JUnit 5 Maven Setup: A Complete Guide to Automated Testing in Java

Introduction to JUnit 5 Maven Setup

In modern software development, automated testing is essential for delivering reliable, maintainable, and high-quality applications. Developers need testing frameworks that can integrate smoothly with their development and build processes. JUnit 5 and Maven are two widely used tools that make Java testing more efficient and manageable.

JUnit 5 provides a modern programming and testing model for Java applications, while Maven simplifies dependency management, project configuration, and test execution. When these technologies are combined, developers can create an efficient automated testing workflow.

This guide explains the JUnit 5 Maven setup process, essential dependencies, project structure, test execution, important JUnit 5 features, and best practices for Java developers and software testers.

What Is JUnit 5?

JUnit 5 is a modern testing framework for Java applications. It provides developers with tools for writing and executing unit tests while offering a more flexible architecture than earlier JUnit versions.

JUnit 5 is built around three major components:

  • JUnit Platform – Provides the foundation for launching testing frameworks on the JVM.

  • JUnit Jupiter – Provides the programming and extension model for writing JUnit 5 tests.

  • JUnit Vintage – Allows JUnit 3 and JUnit 4 tests to run on the JUnit Platform.

JUnit 5 introduces several improvements, including better extensions, parameterized testing, dynamic tests, nested tests, and improved test lifecycle management.

Why Use JUnit 5 with Maven?

Maven is a popular build automation and dependency management tool for Java projects. It uses a pom.xml file to define project information, dependencies, plugins, and build configurations.

Combining Maven with JUnit 5 offers several advantages:

1. Easy Dependency Management

Maven automatically downloads and manages the libraries required by your project. This makes adding JUnit 5 dependencies much easier.

2. Automated Test Execution

Maven can execute your tests as part of the standard build lifecycle. You can run your tests from the command line using:

mvn test

3. Consistent Project Structure

Maven follows a standard project structure, making Java projects easier to understand and maintain.

4. Continuous Integration Support

JUnit 5 and Maven work well with CI/CD environments, allowing automated tests to run whenever developers build or deploy applications.

5. Better Test Organization

Maven separates application code from test code, helping developers maintain a clean and scalable project.

Prerequisites for JUnit 5 Maven Setup

Before configuring JUnit 5 with Maven, make sure your development environment includes:

  • Java Development Kit (JDK)

  • Apache Maven

  • A Java IDE such as IntelliJ IDEA, Eclipse, or Visual Studio Code

  • Basic knowledge of Java programming

  • Basic understanding of Maven and pom.xml

For modern projects, using a currently supported Java LTS version is recommended.

JUnit 5 Maven Project Structure

A typical Maven project can follow this structure:

my-java-project/
├── pom.xml
└── src/
    ├── main/
    │   └── java/
    │       └── com/example/
    │           └── Calculator.java
    └── test/
        └── java/
            └── com/example/
                └── CalculatorTest.java

The src/main/java directory contains application source code, while src/test/java contains test classes.

The pom.xml file is the central configuration file for Maven.

Step-by-Step JUnit 5 Maven Setup

Step 1: Create a Maven Project

Create a new Maven project using your preferred IDE or Maven command-line tools.

Once the project has been created, locate the pom.xml file in the project root directory.

Step 2: Add JUnit 5 Dependency

For a standard JUnit 5 setup, add the JUnit Jupiter dependency to your pom.xml.

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

Using the test scope ensures that the dependency is available for compiling and running tests without becoming part of the application’s production dependencies.

Always verify the current JUnit release before copying a version number into a new project.

Step 3: Configure the Maven Surefire Plugin

The Maven Surefire Plugin is responsible for running tests during Maven’s test phase.

A typical configuration can look like this:

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

For many modern Maven projects, the current Surefire version already provides the necessary JUnit Platform integration. Keeping the plugin version explicit can also make builds more predictable.

Step 4: Create Your First JUnit 5 Test

Suppose you have a simple calculator class:

public class Calculator {

    public int add(int a, int b) {
        return a + b;
    }
}

You can create a test class inside src/test/java:

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void shouldAddTwoNumbers() {
        Calculator calculator = new Calculator();

        int result = calculator.add(10, 20);

        assertEquals(30, result);
    }
}

The @Test annotation identifies the method as a JUnit test.

The assertEquals() method verifies that the actual result matches the expected result.

Step 5: Run JUnit 5 Tests with Maven

Open your terminal in the Maven project directory and run:

mvn test

Maven will compile the project, compile the test classes, execute the tests, and report the results.

If all tests pass, Maven will display a successful build result.

You can also run Maven tests from your IDE using its built-in JUnit and Maven integration.

Important JUnit 5 Features

JUnit 5 provides several features that make automated testing more flexible and maintainable.

1. JUnit 5 Test Annotations

JUnit 5 provides annotations for controlling test execution and lifecycle.

Common annotations include:

  • @Test – Marks a method as a test.

  • @BeforeEach – Runs before each test.

  • @AfterEach – Runs after each test.

  • @BeforeAll – Runs once before all tests in the class.

  • @AfterAll – Runs once after all tests.

  • @Disabled – Temporarily disables a test.

  • @Nested – Organizes related tests into nested classes.

  • @Tag – Categorizes tests.

These annotations help developers organize test cases and control setup and cleanup operations.


2. Parameterized Tests

Parameterized tests allow the same test logic to run with multiple input values.

For example:

@ParameterizedTest
@ValueSource(ints = {2, 4, 6, 8})
void shouldAcceptEvenNumbers(int number) {
    assertEquals(0, number % 2);
}

Instead of creating separate test methods for every input, one test method can validate multiple values.

Parameterized testing can reduce duplicate code and improve test coverage.

3. Assertions

JUnit 5 provides several assertions for validating application behavior.

Examples include:

assertEquals(expected, actual);
assertNotEquals(unexpected, actual);
assertTrue(condition);
assertFalse(condition);
assertNull(value);
assertNotNull(value);

Assertions are fundamental because they determine whether a test passes or fails.

4. Test Lifecycle Management

JUnit 5 provides lifecycle annotations that allow developers to prepare and clean up test environments.

For example:

@BeforeEach
void setUp() {
    // Prepare test data
}

@AfterEach
void tearDown() {
    // Clean up resources
}

This is particularly useful when tests require common setup or cleanup operations.

5. Nested Tests

The @Nested annotation allows developers to group related test scenarios.

This can make large test classes easier to read and maintain.

For example, you might organize tests into groups such as:

  • Successful login

  • Invalid login

  • Password validation

  • Account lockout

JUnit 5 Maven Setup Best Practices

Following best practices can make your automated testing strategy more reliable.

Keep Tests Independent

Each test should ideally run independently of other tests. Avoid creating dependencies between test cases.

Use Descriptive Test Names

A test name should clearly communicate what behavior is being tested.

For example:

shouldCalculateTotalPrice()

is more informative than:

test1()

Follow the Arrange-Act-Assert Pattern

A simple testing structure is:

  1. Arrange – Prepare the required data.

  2. Act – Execute the functionality.

  3. Assert – Verify the expected result.

This makes tests easier to understand.

Avoid Excessive Test Duplication

Use parameterized tests and reusable test utilities where appropriate rather than creating repetitive test methods.

Run Tests Regularly

Run automated tests during development and integrate them into your CI/CD pipeline so that problems are detected early.

JUnit 5 vs JUnit 4

JUnit 5 introduced a new architecture and several improvements over JUnit 4.

Feature JUnit 4 JUnit 5
Architecture Monolithic Modular
Extensions Rules and Runners Extension Model
Parameterized Testing Limited More flexible
Nested Tests Not available Supported
Dynamic Tests Not available Supported
Java 8 Features Limited Stronger support
Platform JUnit-specific JUnit Platform

For new Java projects, JUnit 5 is generally the preferred choice because of its modern architecture and feature set.

Common JUnit 5 Maven Setup Problems

Even with a straightforward configuration, developers may encounter problems.

Tests Are Not Running

If Maven does not detect your tests, check:

  • The test class is located under src/test/java.

  • Test methods use JUnit 5 annotations.

  • JUnit Jupiter dependencies are present.

  • Maven Surefire is compatible with JUnit 5.

  • Your class and method names follow your project’s test-discovery conventions.

Dependency Conflicts

Multiple testing libraries or mixed JUnit versions can sometimes create dependency conflicts.

Use Maven’s dependency tree to investigate:

mvn dependency:tree

JUnit 4 and JUnit 5 Compatibility

Some projects still contain JUnit 4 tests. JUnit Vintage can be used when legacy JUnit 3 or JUnit 4 tests need to run on the JUnit Platform.

However, for new tests, using JUnit Jupiter APIs consistently is usually easier to maintain.

JUnit 5 and Maven in a Software Testing Career

Learning JUnit 5 and Maven can be valuable for Java developers and software testing professionals.

These technologies are commonly relevant to roles such as:

  • Automation Test Engineer

  • Software Test Engineer

  • QA Engineer

  • SDET

  • Java Developer

  • Automation QA Engineer

JUnit 5 can help professionals build automated unit tests, while Maven provides dependency management and repeatable build and test execution.

For learners entering software testing, JUnit 5 can also serve as a foundation for understanding automated testing practices in Java-based projects.

Conclusion

A proper JUnit 5 Maven setup provides a strong foundation for automated testing in Java projects. Maven simplifies dependency management and test execution, while JUnit 5 provides a modern testing platform with features such as parameterized tests, lifecycle management, nested tests, assertions, and extensibility.

To get started, configure your Maven project, add the JUnit Jupiter dependency, configure the Surefire plugin when appropriate, create test classes under src/test/java, and execute your tests with mvn test.

As you become more comfortable with JUnit 5, you can explore advanced concepts such as custom extensions, dynamic tests, parameterized testing, test tagging, integration testing, and CI/CD automation.

Developing strong skills in Java, Maven, JUnit 5, and automated testing can help you build a solid foundation for a career in modern software testing and Java development.

    Scroll to Top