JUnit 5 Gradle Example: Running Tests with Gradle

In this JUnit 5 Gradle example, we will learn how to get the required dependencies for writing JUnit 5 tests with Gradle. Also, we will learn how to configure the JUnit Gradle plugin to run the tests.

This article is part of the JUnit 5 Tutorial.

Required dependencies

Update 18th of June 2018: Beginning from Gradle 4.6 there is now native support for JUnit Jupiter. This means that the configuration is now easier.

First, to be able to write JUnit 5 tests we need the junit-jupiter-api artifact as a dependency in build.gradle:

dependencies {
    testCompile("org.junit.jupiter:junit-jupiter-api:5.2.0")
}

Now all we need is to tell to use the JUnit platform in the tests:

test {
    useJUnitPlatform()
}

Moreover, JUnit 5 uses test engines to run the tests. This means that we have to add JUnit Jupiter test engine to the test runtime classpath:

dependencies {
    testCompile("org.junit.jupiter:junit-jupiter-api:5.2.0")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:5.2.0")
}

Now we have the most basic setup for writing and running JUnit 5 tests with Gradle.

Configuration prior to Gradle 4.6

To be able to write JUnit 5 tests we need the junit-jupiter-api artifact as a dependency just like shown above.

In addition, when using Gradle 4.5 or older, to be able to run JUnit 5 tests we have to configure the JUnit Gradle plugin:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.2.0'
    }
}

apply plugin: 'org.junit.platform.gradle.plugin'

We also need the JUnit Jupiter test engine in the test runtime classpath like shown before.

Now we have the a setup for writing and running JUnit 5 tests with older versions of Gradle.

Running tests

The JUnit Gradle plugin discovers tests under src/test/java directory by default.

Let’s check if our configuration works by adding a very simple test that does nothing:

class GradleExampleTest {

    @Test
    void shouldRun() {

    }
}

Now we can run our tests on the command line with:

$ gradle test

We should see output similar to this:

:test
BUILD SUCCESSFUL in 2s

There we go! JUnit Gradle plugin is now running our tests.

Summary

In this JUnit 5 Gradle example we have learned how to add the required dependency for writing JUnit 5 tests and how to configure JUnit Gradle plugin to be able to run the tests.

The example code for this guide can be found on GitHub.

About the Author

Arho is a software craftsman who wants to learn new things by teaching others. He helps people deliver more valuable software sooner, while maintaining a sustainable development pace.

>