Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Testing and Publishing

Testing with JUnit 5 in Gradle: the test Task

Learn how Gradle runs tests: useJUnitPlatform, test dependencies, filtering with --tests, logging, reports, system properties, parallel forks and failing the build.

Gradle treats tests as first-class build work. The java plugin gives you a test task that compiles src/test, discovers tests with the framework you choose, runs them in a separate JVM, writes reports, and fails the build if any test fails. Because the task declares its inputs and outputs, Gradle skips it when nothing relevant changed.

This lesson covers the setup for JUnit 5, running a single test, controlling the test JVM, reading reports, and making tests reliable. It builds on the Java plugin lesson.

Gradle cannot run on this site. Build files are read-only; the Java stand-in at the end is a tiny JUnit-like runner that really runs on Piston.

The minimal setup

Kotlin
plugins {
    java
}

repositories { mavenCentral() }

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.11.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

Three parts are needed:

  1. the API and engine (junit-jupiter) to compile and run tests,
  2. the launcher on the runtime classpath (required from Gradle 9, and recommended before),
  3. useJUnitPlatform() to tell Gradle which framework to use. Without it Gradle falls back to JUnit 4 and finds no tests.

A test looks like this, in src/test/java/shop/PriceTest.java:

Java
package shop;

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class PriceTest {
    @Test
    void addsTax() {
        assertEquals(120, new Price(100).withTax(20).cents());
    }
}

Run all tests with ./gradlew test.

Running a subset

TEXT
./gradlew test --tests "shop.PriceTest"
./gradlew test --tests "shop.PriceTest.addsTax"
./gradlew test --tests "*Price*"
./gradlew :core:test --tests "shop.*"

Gradle matches the fully qualified class or method name, and * is a wildcard. In build scripts the same idea is a filter:

Kotlin
tasks.test {
    filter {
        includeTestsMatching("shop.fast.*")
        excludeTestsMatching("*Slow*")
    }
}

JUnit 5 tags (@Tag("slow")) are even better for categories:

Kotlin
tasks.test {
    useJUnitPlatform {
        excludeTags("slow")
    }
}

Controlling the test JVM

Tests run in a forked JVM that you configure on the task:

Kotlin
tasks.test {
    useJUnitPlatform()

    maxHeapSize = "512m"
    jvmArgs("-XX:+UseSerialGC")
    systemProperty("user.timezone", "UTC")
    environment("APP_MODE", "test")

    maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1)

    testLogging {
        events("passed", "skipped", "failed")
        showStandardStreams = false
        exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
    }
}

Notes:

  • maxParallelForks runs test classes in several JVMs at once. It speeds up large suites, but tests must not share files or ports.
  • Pinning timezone and locale removes "works on my machine" differences.
  • testLogging decides what appears in the console. For CI, failed with the full exception is usually enough.

Reports and results

After a run, look in:

  • build/reports/tests/test/index.html: a browsable HTML report (open it in a browser),
  • build/test-results/test/*.xml: JUnit XML files that CI systems consume.

If tests fail, Gradle prints the path of the HTML report. Use --continue to run the tests of other projects even when one fails, and failFast = true in tasks.test to stop after the first failure.

Reruns and up-to-date checks

Gradle skips test when classes, resources and the task configuration are unchanged:

TEXT
> Task :test UP-TO-DATE

To force a run use ./gradlew test --rerun (Gradle 7.6+) or cleanTest test. If tests depend on something Gradle cannot see (a database, the current date), declare it as an input or mark the task as never up to date with outputs.upToDateWhen { false }. Better: make tests hermetic.

Common problems

Symptom Likely cause
"No tests found" missing useJUnitPlatform() or wrong engine on classpath
Tests pass in IDE, fail in Gradle different working directory (workingDir) or system properties
Flaky with parallel forks shared state such as a fixed port or temp file
Out of memory raise maxHeapSize
Old tests still run cleanTest clears results

Stand-in: a tiny test runner

JUnit finds methods marked @Test, runs each in isolation, records pass/fail and a summary. This model does the same with a custom annotation and reflection, so you can see what the framework does behind ./gradlew test.

Java Stand-in: a mini JUnit-style runner (not JUnit or Gradle)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The order of methods from reflection is not guaranteed, which is also why real tests must not depend on execution order.

A filter in plain Java

Java Stand-in: --tests pattern matching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Your JUnit 5 tests are not found by ./gradlew test. What is the most likely missing line?

    Gradle defaults to the JUnit 4 runner. useJUnitPlatform() switches the test task to JUnit Platform, which runs JUnit 5 tests.
  2. 2. How do you run only the method addsTax of class shop.PriceTest?

    The --tests option takes a class or method pattern.
  3. 3. Where does Gradle write the HTML test report by default?

    HTML reports go to build/reports/tests/<task name>/ and XML results to build/test-results/.
  4. 4. What must be true before you raise maxParallelForks?

    Parallel forks run test classes concurrently in separate JVMs, so shared resources cause flaky failures.

Summary

  • Add the JUnit BOM, junit-jupiter, the launcher, and useJUnitPlatform().
  • Use --tests, filters and JUnit tags to run subsets.
  • Configure the forked test JVM: heap, system properties, parallel forks and logging.
  • Reports live in build/reports/tests; XML results in build/test-results.
  • Keep tests hermetic so up-to-date checks and parallelism are safe.

Next: Test suites, integration tests and coverage