Sub topic 12
Running Tests with JUnit 5 in Maven and Gradle
A test is a small piece of code that checks whether other code works. A build tool runs your tests on every build. If a test fails, the build stops, so broken code is not packaged and shipped by mistake. This chapter shows how Maven and Gradle find and run JUnit 5 tests, how to read the results, and how to fix the most common problems.
What JUnit 5 Is
JUnit 5 is the most popular testing library for Java. It has three parts:
- JUnit Jupiter is the API you write tests with. It gives you
@TestandassertEquals. - JUnit Platform is the engine room. It finds tests and runs them.
- JUnit Vintage runs old JUnit 4 tests. New projects do not need it.
A build tool does not run tests by itself. It hands them to the JUnit Platform, and the platform runs them and reports back.
The Code Under Test
We use the same small app as earlier chapters. It lives at src/main/java/com/example/App.java.
package com.example;
public class App {
public static void main(String[] args) {
System.out.println(greeting("World"));
}
static String greeting(String name) {
return "Hello, " + name + "!";
}
}The test lives at src/test/java/com/example/AppTest.java. It uses the same package as App, so it can call the package-private greeting method.
package com.example;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class AppTest {
@Test
void greetsByName() {
assertEquals("Hello, Maven!", App.greeting("Maven"));
}
}An assertion is a check that throws an error when it is false. assertEquals(expected, actual) passes when both values match. If they differ, the test fails.
How a Test Run Works
Both tools follow the same steps. They compile the main code, then compile the test code, then run the tests, and only then package the result.
Running Tests with Maven
The setup
Maven needs two things. The first is JUnit as a dependency with test scope. A scope tells Maven where a dependency is used, and test means "only while compiling and running tests." The second is the Surefire plugin. A plugin is an add-on that does work for a build tool, and Surefire is the plugin that runs tests.
<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>com.example</groupId>
<artifactId>hello</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.release>17</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.10.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
</plugins>
</build>
</project>The commands
Surefire runs in the test phase. Every later phase, such as package and verify, runs test first.
mvn test
mvn test -Dtest=AppTest
mvn test -Dtest=AppTest#greetsByName
mvn package -DskipTestsmvn testruns every test.-Dtest=AppTestruns one test class.-Dtest=AppTest#greetsByNameruns one test method.-DskipTestsskips running tests. Use it rarely, and never in your main pipeline.
Which classes Surefire finds
By default, Surefire only runs classes whose names match these patterns:
| Pattern | Example |
|---|---|
| `**/Test*.java` | `TestApp.java` |
| `**/*Test.java` | `AppTest.java` |
| `**/*Tests.java` | `AppTests.java` |
| `**/*TestCase.java` | `AppTestCase.java` |
A class named AppChecks.java is ignored even if it is full of @Test methods.
Reading the results
Maven prints a summary like Tests run: 1, Failures: 0, Errors: 0, Skipped: 0. A failure means an assertion was false. An error means the test threw an exception nobody expected. Detailed reports are written to target/surefire-reports/.
Running Tests with Gradle
The setup
In Gradle, dependency configurations play the role of Maven scopes. testImplementation makes JUnit available to test code only. testRuntimeOnly adds the JUnit Platform launcher, which Gradle needs at run time but your code never imports.
plugins {
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.guava:guava:33.2.1-jre")
testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
application {
mainClass = "com.example.App"
}
tasks.named<Test>("test") {
useJUnitPlatform()
}The launcher line has no version. The junit-jupiter dependency brings along version information for the whole JUnit family, so Gradle picks a matching launcher version.
The commands
./gradlew test
./gradlew test --tests com.example.AppTest
./gradlew test --tests "com.example.AppTest.greetsByName"
./gradlew test --rerun
./gradlew build -x test./gradlew testruns every test.--testsfilters by class or method name. It also accepts wildcards such as"*AppTest".--rerunforces the tests to run again (Gradle 7.6 and later).-x testexcludes the test task. As with Maven's skip flag, use it with care.
Gradle does not care about class names. It runs any class that has @Test methods.
Why tests sometimes do not run again
Gradle remembers its last run. If no code changed since then, it marks the test task UP-TO-DATE and skips it. That saves time, but it can confuse you while you are learning. Use --rerun when you want a fresh run anyway.
Reading the results
Gradle prints a short message and, on failure, the name of the failing test. The full report is a web page at build/reports/tests/test/index.html. Open it in a browser to see every test, how long it took, and its error message.
Maven and Gradle Side by Side
| Task | Maven | Gradle |
|---|---|---|
| Test-only dependency | `<scope>test</scope>` | `testImplementation` |
| Thing that runs tests | Surefire plugin | `test` task |
| Turn on JUnit 5 | Recent Surefire version | `useJUnitPlatform()` |
| Run all tests | `mvn test` | `./gradlew test` |
| Run one class | `-Dtest=AppTest` | `--tests com.example.AppTest` |
| Skip tests | `-DskipTests` | `-x test` |
| HTML or XML reports | `target/surefire-reports/` | `build/reports/tests/test/` |
Common Errors and Fixes
| What you see | Likely cause | Fix |
|---|---|---|
| "Tests run: 0" in Maven | Old Surefire or a class name that does not match | Pin Surefire 3.x, rename the class to end in `Test` |
| No tests run in Gradle | Missing `useJUnitPlatform()` | Add it to the `test` task |
| `package org.junit.jupiter.api does not exist` | JUnit not declared, or the test is in `src/main/java` | Add the dependency, move the test to `src/test/java` |
| Gradle says the test task is `UP-TO-DATE` | Nothing changed since the last run | Run with `--rerun` |
| `greeting(String) is not public` | The test is in a different package | Use the same package as the class under test |
Watching a Test Fail
Try it yourself. Change the expected text in AppTest to "Hi, Maven!" and run mvn test. Maven prints something like this:
expected: <Hi, Maven!> but was: <Hello, Maven!>
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
BUILD FAILUREmvn package would also fail now, and no JAR would be built. That is the point of running tests in the build. Change the text back before you go on.
Exercise
Your Gradle build says "BUILD SUCCESSFUL", but the HTML report shows zero tests, even though AppTest has a @Test method. What is the most likely cause, and how do you fix it?
Show answer
The test task is not set up to use the JUnit Platform, so Gradle looks for JUnit 4 tests and finds none. Add tasks.named<Test>("test") { useJUnitPlatform() } to build.gradle.kts and run ./gradlew test --rerun.
Exercise
You add a test class named GreetingChecks.java to a Maven project, but mvn test does not run it. Why, and what are two ways to fix it?
Show answer
By default, Surefire only runs classes named Test, Test, Tests, or TestCase. You can rename the class to something like GreetingChecksTest.java, or you can configure Surefire's includes setting so it also matches the new name.
Exercise
Write the commands to run only the greetsByName method of com.example.AppTest in Maven and in Gradle.
Show answer
Maven: mvn test -Dtest=AppTest#greetsByName. Gradle: ./gradlew test --tests "com.example.AppTest.greetsByName".