Search

Dark theme | Light theme

December 5, 2022

Gradle Goodness: Configure Test Task With JVM Test Suite

The JVM Test Suite plugin is part of the Java plugin and provides a nice way to configure multiple test types in our build file. Even if we don't have multiple test types we have a default test type, which is used when we run the Gradle test task. Using the test suite DSL we can configure the task of type Test that belongs to a test suite type. The current release of the JVM Test Suite plugin provides a single target for a test suite type with a single Test task. This will probably change in future releases of the plugin so more task of type Test can be created and configured.

We can reference the Test task using the syntax within a JvmTestSuite configuration block:

...
targets {
    all {
        testTask
    }
}
...

Once we have the reference to the Test task we can configure it using all the methods and properties available for this class.

In the following example build script we configure the logging and set a system property for our default Test task:

plugins {
    java
}
    
repositories {
    mavenCentral()
}

testing {
    suites {
        val test by getting(JvmTestSuite::class) {
            useJUnitJupiter()  // We want to use Jupiter engine
            
            targets {
                all {
                    // Here can access the test task for this 
                    // test suite type (we use the default in this example).
                    // The task can be referenced as testTask.
                    // The task is of type Test and we can use all methods
                    // and properties of the Test class.
                    testTask.configure {
                        // We define a system property with key greeting
                        // and value Hello, which can be used in our test code.
                        systemProperties(mapOf("greeting" to "Hello"))
                        
                        // We configure the logging for our tests.
                        testLogging {
                            exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
                            showStandardStreams = true
                        }
                    }
                }
            }
        }
    }
}

Written with Gradle 7.6.