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

JUnit 5 Dependencies

build.gradle:

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

RuleValue
Sourcessrc/test/java
Class name*Test (Surefire/Gradle default patterns)
Annotation@Test on methods

src/main/java/com/example/Calculator.java:

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

bash
./gradlew test

Output ends with BUILD SUCCESSFUL when all tests pass.

Open the HTML report:

text
build/reports/tests/test/index.html

Run a Subset of Tests

Single class:

bash
./gradlew test --tests 'com.example.CalculatorTest'

Single method:

bash
./gradlew test --tests 'com.example.CalculatorTest.addsTwoNumbers'

Pattern:

bash
./gradlew test --tests '*Calculator*'

Assertions and Exceptions

java
@Test
void divideByZeroThrows() {
    assertThrows(ArithmeticException.class, () -> {
        int x = 1 / 0;
    });
}

Common assertions: assertEquals, assertTrue, assertNotNull, assertAll.

Test Logging

Show stdout/stderr from tests:

gradle
tasks.named('test') {
    useJUnitPlatform()
    testLogging {
        events 'passed', 'skipped', 'failed'
        showStandardStreams = true
    }
}

Compare with Maven testing

MavenGradle
Commandmvn test./gradlew test
Configmaven-surefire-plugintest task + useJUnitPlatform()
Reporttarget/surefire-reportsbuild/reports/tests

Mini Example: Failing Test on Purpose

java
@Test
void intentionalFailure() {
    assertEquals(1, 2);
}
bash
./gradlew test

Gradle 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.

What comes next?

Resources and configuration.