To add JUnit to a Maven project, you add the JUnit dependency to your project’s pom.xml, create test classes under src/test/java, and run the tests with Maven.
1. Add JUnit to pom.xml
For modern Java projects, use JUnit 5.
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.13.4</version>
<scope>test</scope>
</dependency>
</dependencies>
If your pom.xml already has a <dependencies> section, add only the <dependency> block inside it.
2. Configure Maven Surefire Plugin
JUnit tests are usually run by the Maven Surefire Plugin. Add this inside the <build> section of your pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.3</version>
</plugin>
</plugins>
</build>
If your project already has a <build> or <plugins> section, merge the plugin into the existing structure instead of duplicating it.
3. Create a Test Class
Maven expects test classes to be placed under:
src/test/java
Example project structure:
my-project
├── pom.xml
└── src
├── main
│ └── java
│ └── org
│ └── kodejava
│ └── Calculator.java
└── test
└── java
└── org
└── kodejava
└── CalculatorTest.java
Example class to test:
package org.kodejava;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Example JUnit 5 test:
package org.kodejava;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CalculatorTest {
@Test
void addShouldReturnSum() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
}
4. Run the Tests
From the project directory, run:
mvn test
Maven will compile your code, compile your tests, and run any matching test classes.
Common test class naming patterns include:
*Test.java
*Tests.java
*TestCase.java
Complete pom.xml Example
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.kodejava</groupId>
<artifactId>junit-maven-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.13.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.3</version>
</plugin>
</plugins>
</build>
</project>
That’s it — after adding the dependency and plugin configuration, you can start writing JUnit tests and run them with mvn test.
