0
0
JUnittesting~5 mins

@EnabledOnJre for JRE-specific tests in JUnit

Choose your learning style9 modes available
Introduction

Sometimes, tests should run only on certain Java versions. @EnabledOnJre helps run tests only on specific Java Runtime Environments (JREs).

You want to test a feature that works only on Java 17 or newer.
Your code uses APIs introduced in a specific Java version.
You want to skip tests on older Java versions to avoid failures.
You maintain a library supporting multiple Java versions and want version-specific tests.
Syntax
JUnit
@EnabledOnJre(JRE.JAVA_VERSION)
void testMethod() {
    // test code
}

Replace JAVA_VERSION with the desired Java version like JAVA_17 or JAVA_11.

This annotation is from org.junit.jupiter.api.condition.EnabledOnJre.

Examples
This test runs only if the JRE is Java 17.
JUnit
@EnabledOnJre(JRE.JAVA_17)
void testOnlyOnJava17() {
    // test code here
}
This test runs on Java 11 or Java 17.
JUnit
@EnabledOnJre({JRE.JAVA_11, JRE.JAVA_17})
void testOnJava11Or17() {
    // test code here
}
Sample Program

This class has two tests. The first runs only on Java 17. The second runs on Java 11 or 17. If run on other versions, these tests are skipped.

JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class JreSpecificTest {

    @Test
    @EnabledOnJre(JRE.JAVA_17)
    void testRunsOnlyOnJava17() {
        assertTrue(System.getProperty("java.version").startsWith("17"));
    }

    @Test
    @EnabledOnJre({JRE.JAVA_11, JRE.JAVA_17})
    void testRunsOnJava11Or17() {
        String version = System.getProperty("java.version");
        assertTrue(version.startsWith("11") || version.startsWith("17"));
    }
}
OutputSuccess
Important Notes

If the current JRE does not match, the test is skipped, not failed.

You can combine this with other conditions like @EnabledOnOs for more control.

Summary

@EnabledOnJre runs tests only on specified Java versions.

Use it to avoid running tests on unsupported Java versions.

Tests are skipped if the JRE does not match, keeping your test results clean.