JUnit – Executing Tests with Maven Build
Last Updated :
03 Oct, 2024
JUnit is a widely-used testing framework for Java that allows developers to create and execute unit tests. When combined with Maven, the build automation tool, it becomes easy to automate the execution of these tests as part of the build lifecycle. In this article, we will explore how JUnit works with Maven, how to set up the project, and how to run the tests efficiently.
Understanding Maven and JUnit Integration
Maven
Maven is a build automation and project management tool that simplifies managing project dependencies, building, testing, and packaging applications. It uses the Project Object Model (POM) file to define project structure, dependencies, and build configurations.
JUnit
JUnit is a Java testing framework used for testing individual units of source code. It allows developers to write test cases for methods and functionalities in isolation and verify that they produce the expected outcomes.
Maven and JUnit Integration
Maven integrates with JUnit through the Maven Surefire Plugin, responsible for running unit tests during the build process. When you run a Maven build, the Surefire Plugin automatically detects and runs test cases located in the src/test/java
directory. These test cases are typically written using JUnit.
Maven follows a build lifecycle, where each lifecycle phase performs a specific task. The test phase is the step in the lifecycle where Maven runs the JUnit tests.
Lifecycle Phases in Maven:
- compile: Compiles the source code.
- test: Runs unit tests using the Surefire Plugin and JUnit.
- package: Packages the compiled code into a JAR or WAR file.
- install: Installs the built package into the local Maven repository.
JUnit Testing with Maven
This example project demonstrates how to set up JUnit tests with Maven. The project includes a simple Java class (Calculator
) with methods to add and subtract numbers, along with the corresponding JUnit test class (CalculatorTest
) to validate these methods.
Step 1: Create a New Maven Project
Create a new Maven project using IntelliJ IDEA. Choose the following options:
- Name:
JUnitMavenExample
- Build system: Maven
- Click on the Create button.
Project Structure
After the project creation done successfully, then the folder structure will look like the below image:
Step 2: Add Dependencies to pom.xml
Open the pom.xml
file and add the JUnit dependency, which is necessary for running the JUnit tests.
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg</groupId>
<artifactId>JUnitMavenExample</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- JUnit dependency for testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope> <!-- Indicates that this dependency is only required for the test phase -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
</project>
The JUnit dependency is included with the test scope, meaning it's only used during the test phase. The maven-surefire-plugin
ensures the tests are executed during the build process.
Step 3: Create the Calculator Class
Create the Calculator
class, which will have basic arithmetic methods: add()
and subtract()
.
Calculator.java
Java
package com.gfg;
public class Calculator {
// Method to add two numbers
public int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
// Method to subtract one number from another
public int subtract(int a, int b) {
return a - b; // Returns the difference of a and b
}
}
- add(int a, int b): This method adds the two numbers and returns the result.
- subtract(int a, int b): This method subtracts the second number from the first number.
Step 4: Create the Main Class
Create the Main
class to perform the basic arithmetic operations and demonstrate the use of the Calculator
class.
Main.java
Java
package com.gfg;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
// Example of adding two numbers
int sum = calculator.add(5, 3);
System.out.println("Sum of 5 and 3 is: " + sum);
// Example of subtracting two numbers
int difference = calculator.subtract(5, 3);
System.out.println("Difference of 5 and 3 is: " + difference);
}
}
The main
method allows for the standalone execution of the class. It demonstrates the use of the add
and subtract
methods by creating an instance of the Calculator
class and printing the results to the console.
Step 5: Create the JUnit Test Class
Create the CalculatorTest
class containing test methods to verify the functionality of the Calculator
class.
CalculatorTest.java
Java
import com.gfg.Calculator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
// Instantiate the Calculator object
Calculator calculator = new Calculator();
// Test for the add method
@Test
public void testAdd() {
int result = calculator.add(2, 3); // Calls the add method
assertEquals(5, result); // Verifies if 2 + 3 equals 5
}
// Test for the subtract method
@Test
public void testSubtract() {
int result = calculator.subtract(5, 3); // Calls the subtract method
assertEquals(2, result); // Verifies if 5 - 3 equals 2
}
}
- testAdd(): Checks if the
add()
method of the Calculator
returns the correct sum. - testSubtract(): Verifies the output of the
subtract()
method. assertEquals(expected, actual)
: Asserts that the expected and actual values are the same.
Step 6: Run the Application
Once the project is complete, run the Main
class, and you should see the following output:
Step 7: Run the Tests with Maven
To execute the tests, run the following Maven command in the project directory:
mvn test
This command compiles the code and runs the test cases located in the src/test/java
directory.
Test Results:
Step 8: Generated Test Report
Maven's Surefire Plugin automatically generates a test report in the target/surefire-reports/
directory.
- Surefire report file:
target/surefire-reports/CalculatorTest.txt
This file contains a detailed log of the test execution, including pass/fail status and stack traces for any failed tests.
This example project demonstrates how to set up the Maven project to work with JUnit, including, Creating the simple Calculator class with arithmetic methods and writing the corresponding the JUnit test class to verify the behavior of the Calculator class, Running the tests using the Maven command (mvn test) and viewing the generated reports.
Conclusion
Integrating JUnit with Maven allows developers to automate testing as part of the build lifecycle, ensuring code quality and minimizing bugs. By understanding Maven's build lifecycle and configuring the Surefire Plugin, you can customize how and when tests are executed, generate reports, and optimize the testing process. For more advanced testing strategies, consider exploring JUnit 5 and its new features, such as parameterized tests and dynamic tests.
Similar Reads
Building a Java Project with Maven
Maven is one of the most popular build automation tools. It is developed using the Java programming language and is primarily used for Java-based projects. However, it has been updated to support programming languages like C#, Ruby, and more. This article will teach us how to build a Java project wi
2 min read
JUnit 5 â Test Execution Order
In JUnit 5, the Test execution order is not in the order by default. Every Test is randomly executed one after the other. There is no compulsion that the test which is on top will be executed first and the test which is in bottom will be executed last. So, the order of execution of test cases is unp
4 min read
Why Maven Doesnât Find JUnit Tests to Run?
When Maven fails to find JUnit tests to run, it can be frustrating and disrupt the development process. Several common issues can cause this problem, ranging from incorrect directory structures, missing dependencies, and to misconfigured plugins. One common issue developers face when using Maven is
2 min read
JUnit 5 - Test Suites with Example
JUnit 5 encourages a modular approach to test creation with its test suites. These suites function as containers, bundling multiple test classes for easier management and collective execution within a single run. In this article, we will learn about JUnit 5 - Test Suites. Test SuiteIn JUnit 5, a tes
2 min read
JUnit 5 â Execute Test in Eclipse
JUnit is one of the widely used unit testing frameworks for Java-based Applications. We have different versions and upgrades published by JUnit 5, the latest version available in JUnit is JUnit 5. JUnit 5 is the upgraded version of JUnit 4, which is launched to support various latest features of Jav
10 min read
JUnit 5 â Conditional Test Execution
JUnit is one of the popular unit testing frameworks for Java projects. JUnit 5 is the latest version provided by the JUnit team launched with the aim of supporting the latest Java features and also providing notable advanced features to its predecessor JUnit 4. In this article, we will discuss one o
8 min read
Adding JGit to the Project with Maven
Integrating the JGit with Maven not only enhances the project version control capabilities but also streamlines workflow processes by leveraging the Maven build and dependency management system. This article will guide you through the steps of adding JGit to the Maven project and enabling you to har
3 min read
Tagging and Filtering JUnit Tests
JUnit is a widely used testing framework for Java applications that allows developers to write unit tests for their code. One of its powerful features is the ability to tag and filter tests. This feature is useful when running a subset of the tests under different conditions, such as during developm
9 min read
Encode and Decode Strings in Java with JUnit Tests
Strings are very useful and they can contain sequences of characters and there are a lot of methods associated with Strings. Moreover, encoding and decoding are possible for a given use case and it can be validated whether are they equal or not for a given requirement. They can be tested for validit
4 min read
How to execute TestNG and Maven without testng.xml file?
To run TestNG tests with Maven, it is not mandatory to configure any testng.xml. Instead of this you just let Maven do the execution with maven-surefire-plugin of the Maven build lifecycle and for that you don't need to define any test suite, classes, or methods in testng.xml. The maven-surefire-plu
2 min read