If you want to unit test your Java code using the most up-to-date JUnit 5 testing framework, Gradle offers full support.

In this article, you’ll learn what configuration to add to your Gradle Kotlin build script to run tests. We’ll cover the best approach, available since Gradle 7.3, with no need to configure any dependencies or versions.

What is JUnit 5?

JUnit 5 is the long-awaited successor to JUnit 4, with new features like:

  • tagging
  • parameterized tests
  • useful new test assertions

Importantly, rather than being bundled into a single library like JUnit 4, JUnit 5 comprises multiple libraries that can be added to your project depending on your needs. For example, junit-jupiter-params should be added to use parameterized tests.

If you’ve heard the term JUnit Jupiter, that’s just the part of JUnit 5 that offers a new programming model for writing tests. You can use the terms JUnit 5 & JUnit Jupiter interchangeably, but in this article we’ll use the former.

Requirements for using JUnit 5 with Gradle

Before configuring a build script to run JUnit 5 tests, first make sure your project meets the below standards.

It needs Gradle version 4.6 or later to use JUnit 5. To check your version, just pass the --version command-line option.

$ ./gradlew --version

------------------------------------------------------------
Gradle 8.2.1
------------------------------------------------------------

Build time:   2023-07-10 12:12:35 UTC
Revision:     a38ec64d3c4612da9083cc506a1ccb212afeecaa

Kotlin:       1.8.20
Groovy:       3.0.17
Ant:          Apache Ant(TM) version 1.10.13 compiled on January 4 2023
JVM:          19.0.2 (Eclipse Adoptium 19.0.2+7)
OS:           Windows 11 10.0 amd64

Also, the Gradle project where you want to run JUnit 5 tests should apply either the java or java library plugins. Configure that in your build.gradle.kts build script.

plugins {
    java
}

You can use JUnit to test other JVM languages such as Kotlin, but we’ll focus on Java in this article.

Finally, ensure you declare a repository from which Gradle can pull JUnit 5 dependencies. Normally, this is Maven Central:

repositories {
    mavenCentral()
}

Configuring JUnit 5 in the Gradle Kotlin DSL

The most up-to-date way to configure Gradle to use JUnit 5 is with the JVM Test Suite plugin.

The plugin, released in Gradle 7.3, lets you easily configure different suites of tests, such as unit tests and integration tests. Conveniently, the plugin is automatically applied when using the java or java-library plugins.

The plugin comes preconfigured with a test suite for unit tests called test. We just need to configure it in our build script to use JUnit 5:

testing {
    suites {
        val test by getting(JvmTestSuite::class) {
            useJUnitJupiter()
        }
    }
}

So what does this do?

  • accesses the JVM Test Suite plugin configuration
  • fetches the test suite named test
  • configures the test suite to use JUnit 5 with useJUnitJupiter()

The plugin also automatically configures the JUnit 5 dependencies needed to start writing unit tests. That’s right! There’s no need to add anything else to our build script’s dependencies configuration.

Writing a JUnit 5 test

Now that Gradle’s setup for JUnit 5, let’s write a unit test to check that it’s working.

Gradle expects unit tests in a src/test/java directory. Within a com.tomgregory package, we’ll add a simple example test ExampleTest.java.

package com.tomgregory;

import org.junit.jupiter.api.Test;

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

public class ExampleTest {
    @Test
    public void canWriteASimpleTest() {
        assertEquals("Amaze me", "Amaze" + " me");
    }
}

Note that we import the @Test annotation and assertEquals assertion method from the org.junit_jupiter package. This means this test is definitely using JUnit 5.

Running JUnit 5 tests in Gradle

With a unit test in place, we simply run Gradle’s test task from the command line to run it.

$ ./gradlew test

BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed

Success! To validate that the test actually ran, navigate to build/reports/tests/test/index.html to view the test report.

Test Summary
1
tests

0
failures

0
ignored

0.015s
duration

100%
successful

If we run the tests again, Gradle knows they already successfully ran and skips them, saving a lot of time. That’s shown below by the text 2 up-to-date.

$ ./gradlew test

BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 up-to-date

Avoid running the clean task if you want to use this feature.

JUnit 5 dependencies

The JVM Test Suite plugin brings in the following JUnit 5 dependencies.

  • org.junit.jupiter:junit-jupiter
  • org.junit.platform:junit-platform-launcher

There are also other transitive dependencies. You can view them with the dependencies task, specifying either the test compile or runtime classpaths.

$ ./gradlew dependencies --configuration testCompileClasspath

> Task :dependencies

------------------------------------------------------------
Root project 'gradle-junit-5-example'
------------------------------------------------------------

testCompileClasspath - Compile classpath for source set 'test'.
\--- org.junit.jupiter:junit-jupiter:5.8.2
... (truncated for brevity)

You see in the output that Gradle uses a specific JUnit 5 version e.g. Gradle 8.2.1 uses JUnit 5.8.2. You can override the JUnit 5 version by passing your preferred version string to the useJUnitJupiter() function.

testing {
    suites {
        val test by getting(JvmTestSuite::class) {
            useJUnitJupiter("5.10.0")
        }
    }
}

This way, you can move to the latest JUnit 5 version as soon as it’s released, rather than waiting for Gradle to bump the version.

Adding other dependencies

If you need any other dependencies available to your unit tests, you can add them to the same JVM Test Suite configuration. For example, let’s configure the fluent assertions library AssertJ.

testing {
    suites {
        val test by getting(JvmTestSuite::class) {
            useJUnitJupiter()
            dependencies {
                implementation("org.assertj:assertj-core:3.24.2")
            }
        }
    }
}

Now our unit test can use the AssertJ version of assertThat.

package com.tomgregory;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class ExampleTest {
    @Test
    public void canWriteASimpleTest() {
        assertThat("Amaze" + " me").isEqualTo("Amaze me");
    }
}

If you prefer, you can instead declare the dependency in the standard dependencies configuration of your build script.

dependencies {
    testImplementation("org.assertj:assertj-core:3.24.2")
}

Remember to change the dependency configuration name from implementation to testImplementation.

Using JUnit 5 in older Gradle versions (legacy)

If you’re using a version of Gradle prior to 7.3 or you prefer not to use the JVM Test Suite plugin, you can still use JUnit 5.

Just configure the test task manually and remember to add the relevant JUnit 5 dependencies.

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

tasks.named<Test>("test") {
    useJUnitPlatform()
}

Writing your unit tests and running them is the same as described above.

Final thoughts

You’ve seen how easy it is to configure your Gradle project to run JUnit 5 unit tests.

Newer projects can use the most up-to-date JVM Test Suite plugin, so you don’t even have to configure the JUnit 5 dependencies yourself. Now you can focus on writing your unit tests and making the most of the new JUnit 5 features.

To take your tests to the next level, learn how to run integration tests in Gradle.

Resources

For reference, here’s my full recommended build.gradle.kts Kotlin build script.

plugins {
    java
}

repositories {
    mavenCentral()
}

testing {
    suites {
        val test by getting(JvmTestSuite::class) {
            useJUnitJupiter()
        }
    }
}

Stop reading Gradle articles like these

This article helps you fix a specific problem, but it doesn't teach you the Gradle fundamentals you need to really help your team succeed.

Instead, follow a step-by-step process that makes getting started with Gradle easy.

Download this Free Quick-Start Guide to building simple Java projects with Gradle.

  • Learn to create and build Java projects in Gradle.
  • Understand the Gradle fundamentals.