Testing with Gradle
Introduction
Gradle runs tests as part of the test task—compile test sources, execute JUnit, and write HTML reports under build/reports/tests. This chapter wires JUnit 5, writes a first test, and shows how to filter tests and read failures.
Prerequisites
- Gradle plugins (
javaplugin) - Basic Java classes
JUnit 5 Dependencies
build.gradle:
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
}
tasks.named('test') {
useJUnitPlatform()
}testImplementation keeps JUnit off the production classpath. useJUnitPlatform() is required for JUnit 5 (Jupiter).
Reload Gradle in IDEA after editing.
Test Layout and Naming
| Rule | Value |
|---|---|
| Sources | src/test/java |
| Class name | *Test (Surefire/Gradle default patterns) |
| Annotation | @Test on methods |
src/main/java/com/example/Calculator.java:
package com.example;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}src/test/java/com/example/CalculatorTest.java:
Run Tests
./gradlew testOutput ends with BUILD SUCCESSFUL when all tests pass.
Open the HTML report:
build/reports/tests/test/index.htmlRun a Subset of Tests
Single class:
./gradlew test --tests 'com.example.CalculatorTest'Single method:
./gradlew test --tests 'com.example.CalculatorTest.addsTwoNumbers'Pattern:
./gradlew test --tests '*Calculator*'Assertions and Exceptions
@Test
void divideByZeroThrows() {
assertThrows(ArithmeticException.class, () -> {
int x = 1 / 0;
});
}Common assertions: assertEquals, assertTrue, assertNotNull, assertAll.
Test Logging
Show stdout/stderr from tests:
tasks.named('test') {
useJUnitPlatform()
testLogging {
events 'passed', 'skipped', 'failed'
showStandardStreams = true
}
}Compare with Maven testing
| Maven | Gradle | |
|---|---|---|
| Command | mvn test | ./gradlew test |
| Config | maven-surefire-plugin | test task + useJUnitPlatform() |
| Report | target/surefire-reports | build/reports/tests |
Mini Example: Failing Test on Purpose
@Test
void intentionalFailure() {
assertEquals(1, 2);
}./gradlew testGradle marks build FAILED and points to the HTML report for stack traces—fix the assertion, rerun ./gradlew test.
FAQ
Tests not discovered?
Ensure useJUnitPlatform() is set and class name matches *Test or use @Test in a class Gradle includes (JUnit 5 default engine).
BUILD SUCCESSFUL but 0 tests?
Empty src/test/java or wrong package path—check directory mirrors main sources.
Skip tests in CI temporarily?
-x test on build—avoid for release pipelines.