Verify method behavior only on Java 17 runtime
Preconditions (2)
✅ Expected Result: The test runs and passes only if the runtime is Java 17; otherwise, it is skipped.
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.assertEquals; public class JreSpecificTest { // Method that behaves differently on Java 17 public String getFeatureMessage() { // Simulate behavior return "Feature available on Java 17"; } @Test @EnabledOnJre(JRE.JAVA_17) void testFeatureMessageOnJava17() { String message = getFeatureMessage(); assertEquals("Feature available on Java 17", message, "Message should match on Java 17"); } }
This test class uses @EnabledOnJre(JRE.JAVA_17) to run the test only when the runtime is Java 17. The getFeatureMessage() method simulates a feature that is specific to Java 17. The test asserts that the returned message matches the expected string. If the test runs on any other JRE version, it will be skipped automatically by JUnit 5.
This approach keeps the test clean and focused on the Java 17 environment without manual version checks inside the test code.
Now add tests for Java 11 and Java 17 using @EnabledOnJre with different expected messages
@EnabledOnJre annotation in JUnit?@EnabledOnJre?@EnabledOnJre(JRE.JAVA_17).@EnabledOnJre({JRE.JAVA_11, JRE.JAVA_17}), what happens when running on Java 15?@EnabledOnJre(JRE.JAVA_8, JRE.JAVA_11)@EnabledOnJre({JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_17}). @EnabledOnJre(JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_17) misses braces, C uses strings instead of enums, D uses a wrong attribute name.Pass the test and this pattern moves unknown