Skip to content
javahacks.dev
JUnit

How to Run JUnit 5 Tests From Gradle Builds and CI

Run JUnit 5 from Gradle: useJUnitPlatform, dependencies with the BOM, test filtering, logging, parallel forks, tags and reports for CI.

6 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, Gradle, Docker and Selenium logos.

Gradle runs JUnit 4 by default, and it does not guess that your tests are JUnit 5. The classic symptom is a green build that executed zero tests. This guide sets up Gradle 9 with JUnit 5.13 on JDK 25 so that tests run, can be filtered, are fast and leave reports a CI server can read. The steps are in the order a build needs them.

Step 1: dependencies and the test task

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

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

The BOM pins the Jupiter API, engine and params artifacts to one version, so you never list a version on the other lines. The launcher is declared explicitly because Gradle 9 no longer supplies it from its own distribution. Leave it out and the run fails with a message about the launcher not being on the classpath, as described under common problems below. With the Spring Boot plugin applied, its dependency management already pins JUnit, so the BOM line can go.

useJUnitPlatform() is the line that matters most. Without it Gradle selects the JUnit 4 runner, finds no @RunWith classes, reports success and says nothing.

Step 2: run the tests you mean to run

Shell
./gradlew test
./gradlew test --tests "com.example.OrderServiceTest"
./gradlew test --tests "*OrderService*.cancels*"
./gradlew test --rerun

--tests takes class and method patterns with wildcards. The second form runs one class, the third runs every method starting with cancels in any class matching OrderService. Gradle treats a task whose inputs have not changed as up to date and prints UP-TO-DATE, so a second run after no edits executes nothing. --rerun forces it, and cleanTest is the older spelling of the same idea. Maven users have the equivalent problem in JUnit 5 tests not running in Maven.

Step 3: separate the slow tests

Tags let one source set serve two speeds.

java
@Tag("integration")
class OrderRepositoryIT {
    // needs a database container
}
kotlin
tasks.test {
    useJUnitPlatform { excludeTags("integration") }
}

val integrationTest by tasks.registering(Test::class) {
    testClassesDirs = sourceSets.test.get().output.classesDirs
    classpath = sourceSets.test.get().runtimeClasspath
    useJUnitPlatform { includeTags("integration") }
    shouldRunAfter(tasks.test)
}

The second task reuses the test classes and filters the other way, so ./gradlew test stays quick and ./gradlew integrationTest runs the rest. Without the two lines that set testClassesDirs and classpath, a registered Test task has no classes to scan and finishes instantly with nothing run. The tagging rules, including combining tags, are in JUnit tags.

Step 4: speed it up, measured

kotlin
tasks.test {
    maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1)
    systemProperty("junit.jupiter.execution.parallel.enabled", "true")
}

These are two different mechanisms. maxParallelForks starts several test JVMs and splits test classes between them, which is safe for almost any suite and costs JVM startup per fork. The system property turns on parallel execution inside one JVM, which is faster for many small tests but requires that tests share no mutable state. Turn on one, time it with --rerun, then decide about the other. Both are discussed with their traps in JUnit parallel execution, and the wider build tuning is in speeding up Gradle builds.

Step 4b: see why a test failed without opening a report

The default Gradle output shows FAILED and a pointer to the report, which sends you to a browser for every failure. The testLogging block in step 1 already prints the exception. Two more settings help on a CI log that nobody downloads artifacts from.

kotlin
tasks.test {
    testLogging {
        showStandardStreams = false
        showCauses = true
        showStackTraces = true
        displayGranularity = 2
    }
    reports.html.required = true
    reports.junitXml.required = true
}

showStandardStreams stays off so passing tests do not flood the log with their own System.out. Failing tests still get their output attached in the XML report. displayGranularity = 2 prints failures at method level rather than class level. When one test hangs, the --info flag shows which test is running, and a per-test timeout is the permanent fix, covered in JUnit timeouts.

Step 4c: configure JUnit itself in one file

Parallelism, display name generation and timeouts are JUnit properties, and they do not belong in build.gradle.kts. Put them in src/test/resources/junit-platform.properties, where the IDE and Gradle both read them.

properties
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = same_thread
junit.jupiter.execution.parallel.mode.classes.default = concurrent
junit.jupiter.testinstance.lifecycle.default = per_method

That set runs test classes concurrently and the methods inside a class one after another, which is the safest useful default. The file's full option list is in junit-platform.properties. One advantage of the file over the system property in step 4 is that a developer running a single class from the IDE gets the same behaviour as CI.

Step 5: reports and CI

Gradle writes an HTML report to build/reports/tests/test/index.html and one JUnit XML file per class to build/test-results/test. CI systems read the XML for their test summary and the HTML is for people.

YAML
- run: ./gradlew test
- uses: actions/upload-artifact@v4
  if: always()
  with:
    name: test-results
    path: build/reports/tests

if: always() is the part people forget. A failing test makes the job fail, and without it the report upload step is skipped at exactly the moment you want it.

When it still does not work

If Gradle prints No tests found for given includes, the filter matched nothing. Check the pattern against the fully qualified class name, and check the class is in src/test/java, not src/main. If the log shows Failed to load JUnit Platform, the launcher dependency is missing from testRuntimeOnly. If old tests are skipped while new ones run, they are JUnit 4 and need the Vintage engine or a migration, covered in JUnit 4 to 5. If tests pass in the IDE and fail on the command line, set IntelliJ to run tests through Gradle so both use the same configuration.

A check that the setup really runs tests

A green build proves nothing about a suite that executed zero tests, so confirm the count once. Run ./gradlew test --rerun and open build/test-results/test. Each executed class leaves a TEST-*.xml file with a tests="N" attribute. An empty directory after a successful build means useJUnitPlatform() is missing or the classes are in the wrong source set. Doing this check once per new module costs thirty seconds, and it catches the mistake that otherwise lives for months.

Gradle versions and the launcher warning

On Gradle 8 the missing launcher produced a deprecation warning, and on Gradle 9 it became a failure. If a build passes locally and fails on an agent, compare the Gradle versions first, because the wrapper pins the build tool but a custom CI image may run its own. Printing ./gradlew --version at the start of the pipeline takes a second and removes a whole class of confusion.

What this does not cover

Maven projects configure Surefire, not the test task, and a first-time reader should start with JUnit 5 for beginners. Android Gradle builds run unit tests through their own task types. Sources: Gradle testing on the JVM and the JUnit 5 user guide.

Also inDevOps
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.