Sub topic 12
Running Tests with JUnit 5 in Maven and Gradle
A unit test is a small piece of code that checks one piece of your program. JUnit 5 is the most common testing library for Java. Both Maven and Gradle can find your tests, run them, and stop the build if any test fails. Nobody has to remember to run the tests by hand, because the build does it for you.
The Test Itself
Test classes go in src/test/java, in the same package as the code they check. This test checks the greeting method in App:
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"));
}
}@Test is an annotation, a label that tells JUnit "this method is a test." assertEquals is an assertion, a check that two values match. If they don't match, the test fails.
Running Tests in Maven
Maven runs tests with a plugin called Surefire. A plugin is an add-on that does one job in the build. Your pom.xml needs two things: JUnit as a test-scoped dependency, and a recent Surefire version that understands JUnit 5.
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>The Surefire plugin is pinned to version 3.2.5 in the <build> section of the POM from the earlier chapter. Then run:
mvn test
mvn test -Dtest=AppTestThe first command runs every test. The second runs only AppTest. Maven saves reports in target/surefire-reports.
Running Tests in Gradle
Gradle needs to be told to use the JUnit Platform. The JUnit Platform is the part of JUnit 5 that finds and launches tests.
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.named<Test>("test") {
useJUnitPlatform()
}Then run:
./gradlew test
./gradlew test --tests com.example.AppTestGradle writes an HTML report to build/reports/tests/test/index.html. Open it in a browser to see which tests passed.
What Happens When a Test Fails
Both tools compile your tests and run them before packaging. If a test fails, the build stops, and no broken JAR gets made.
| Task | Maven | Gradle |
|---|---|---|
| Run all tests | `mvn test` | `./gradlew test` |
| Run one class | `mvn test -Dtest=AppTest` | `./gradlew test --tests com.example.AppTest` |
| Report location | `target/surefire-reports` | `build/reports/tests/test` |
Exercise
You change App.greeting to return "Hi, " + name + "!" and run mvn package. What happens, and why?
Show answer
The build fails. The package phase runs the test phase first, greetsByName expects "Hello, Maven!" but gets "Hi, Maven!", and Maven stops before it makes the JAR.
Exercise
Your Gradle build says "BUILD SUCCESSFUL" but the report shows 0 tests. What is the most likely cause?
Show answer
The test task is missing useJUnitPlatform(), so Gradle never looks for JUnit 5 tests.