Testing / JUnit6 Interview Questions
What is conditional test execution in JUnit 6 and what built-in conditions are available?
JUnit 6 provides condition annotations that skip or enable tests based on runtime conditions without writing assumption code inside the test body. These are implemented as extensions using the ExecutionCondition interface.
| Annotation | Skips test when... |
|---|---|
| @EnabledOnOs / @DisabledOnOs | Running on a specific OS (e.g. WINDOWS, LINUX, MAC) |
| @EnabledOnJre / @DisabledOnJre | Running on a specific Java version range |
| @EnabledForJreRange / @DisabledForJreRange | JRE is inside or outside a specified version range |
| @EnabledIfSystemProperty / @DisabledIfSystemProperty | A system property matches (or doesn't match) a regex |
| @EnabledIfEnvironmentVariable | An environment variable matches a regex |
| @EnabledIf / @DisabledIf | A static boolean method returns false / true |
import org.junit.jupiter.api.condition.*; class ConditionalTests { @Test @EnabledOnOs(OS.LINUX) void linuxOnlyTest() { ... } @Test @DisabledOnOs({OS.WINDOWS, OS.MAC}) void notOnWindowsOrMac() { ... } @Test @EnabledOnJre(JRE.JAVA_21) void java21Feature() { ... } @Test @EnabledForJreRange(min = JRE.JAVA_17, max = JRE.JAVA_21) void java17to21Only() { ... } @Test @EnabledIfEnvironmentVariable(named = "ENV", matches = "CI") void ciOnlyTest() { ... } @Test @EnabledIfSystemProperty(named = "db.available", matches = "true") void databaseTest() { ... } // @EnabledIf: call a custom static method @Test @EnabledIf("isWeekend") void weekendTest() { ... } static boolean isWeekend() { DayOfWeek day = LocalDate.now().getDayOfWeek(); return day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY; } }
More Related questions...