Enable Junit 5 Test Cases Based on Java System Properties

2020 Aug 26

JUnit 5 supports disabling test cases via the @Disabled annotation. Sometimes, you may want some cases to be conditionally disabled or enabled. JUnit 5 provides many annotations to support conditional test execution, like @EnabledOnOs(MAC), @DisabledOnJre(JAVA_8) and @EnabledIfEnvironmentVariable.

Let’s say, a test case only runs when a Java system property is set to a certain value. To do it, add @EnabledIfSystemProperty onto the test case.

@Test
@EnabledIfSystemProperty(named = "foo.enabled", matches = "on")
void fooTest() {
}

The fooTest runs only when the foo.enabled system property is set to on. To run this test case via Gradle, type the command below.

./gradlew test --tests '*.fooTest' -i -Dfoo.enabled=on

To make the JVM running the test case know the Java system property passed to the JVM running Gradle, add below lines in the build.gradle file.

test {
    systemProperty "foo.enabled", System.getProperty("foo.enabled")
}