import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIf; public class EnvTest { @Test @EnabledIf(expression = "'prod'.equals(System.getProperty('env'))", reason = "Only runs in prod environment") void testOnlyInProd() { System.out.println("Running in prod"); } }
The @EnabledIf annotation runs the test only if the expression evaluates to true. Since System.getProperty('env') returns 'prod', the expression 'prod'.equals('prod') is true, so the test runs and prints the message.
When a test is disabled by @EnabledIf, JUnit aborts the test execution by throwing TestAbortedException. So asserting that this exception is thrown confirms the test was skipped.
In Java, '==' compares object references, not string content. The expression should use '.equals()' to compare string values. Using '==' causes the expression to be false, so the test is disabled.
The expression in @EnabledIf can access system properties and environment variables through predefined variables like 'systemProperties' and 'environment'. It cannot execute arbitrary Java code or have side effects.
import org.junit.jupiter.api.extension.ConditionEvaluationResult; import org.junit.jupiter.api.extension.ExecutionCondition; import org.junit.jupiter.api.extension.ExtensionContext; import java.time.DayOfWeek; import java.time.LocalDate; public class WeekdayCondition implements ExecutionCondition { @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { DayOfWeek day = LocalDate.now().getDayOfWeek(); if (day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY) { return ConditionEvaluationResult.disabled("Weekend - test disabled"); } else { return ConditionEvaluationResult.enabled("Weekday - test enabled"); } } }
To create a custom condition for @EnabledIf, implement ExecutionCondition and override evaluateExecutionCondition to return enabled or disabled results. Returning null or wrong interface will not work.