We use @EnabledIf to run tests only when certain conditions are true. This helps save time by skipping tests that don't apply.
Custom conditions with @EnabledIf in JUnit
@EnabledIf(expression = "${condition}")
void testMethod() {
// test code
}The expression is a Spring Expression Language (SpEL) string.
Conditions can check system properties, environment variables, or custom methods.
@EnabledIf(expression = "${os.name} == 'Linux'")
void testOnlyOnLinux() {
// test code
}@EnabledIf(expression = "${systemProperties['user.name']} == 'admin'")
void testForAdminUser() {
// test code
}isDatabaseAvailable() returns true.@EnabledIf(expression = "@myConditionChecker.isDatabaseAvailable()")
void testIfDatabaseIsUp() {
// test code
}This class has two tests. The first runs only if the environment variable TEST_MODE is set to 'true'. The second runs only on Windows OS.
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIf; public class CustomConditionTest { @Test @EnabledIf(expression = "${env.TEST_MODE} == 'true'", reason = "Runs only if TEST_MODE environment variable is true") void testRunsOnlyInTestMode() { System.out.println("Test is running because TEST_MODE is true"); } @Test @EnabledIf(expression = "${os.name}.toLowerCase().contains('windows')", reason = "Runs only on Windows OS") void testRunsOnlyOnWindows() { System.out.println("Test is running on Windows OS"); } }
Make sure the condition expression is valid SpEL syntax.
Use the reason attribute to explain why a test is enabled or disabled.
Environment variables and system properties can be accessed in expressions.
@EnabledIf lets you run tests only when a condition is true.
Conditions use Spring Expression Language (SpEL) for flexibility.
This helps run tests smartly based on environment or custom logic.
Practice
@EnabledIf in JUnit tests?Solution
Step 1: Understand the role of @EnabledIf
@EnabledIf is used to conditionally enable a test based on a custom boolean expression or method.Step 2: Compare with other annotations
Unlike disabling or repeating tests, @EnabledIf controls test execution dynamically based on conditions.Final Answer:
To run a test only if a custom condition returns true -> Option AQuick Check:
@EnabledIf runs test if condition true [OK]
- Confusing @EnabledIf with @Disabled
- Thinking it repeats tests
- Assuming it marks tests as expected failures
isFeatureEnabled() returns true using @EnabledIf?Solution
Step 1: Check correct attribute name
The correct attribute for the condition expression is unnamed, so just a string is passed to @EnabledIf.Step 2: Validate method call syntax
The method must be called with parentheses inside the string: "isFeatureEnabled()".Final Answer:
@EnabledIf("isFeatureEnabled()") -> Option AQuick Check:
Use @EnabledIf("method()") syntax [OK]
- Using expression attribute which does not exist
- Omitting parentheses in method call
- Using incorrect attribute name like condition
public class FeatureTest {
static boolean isFeatureEnabled() { return false; }
@Test
@EnabledIf("isFeatureEnabled()")
void testFeature() {
System.out.println("Feature test executed");
}
}Solution
Step 1: Evaluate the condition method
The method isFeatureEnabled() returns false, so the condition for @EnabledIf is false.Step 2: Understand @EnabledIf behavior
When the condition is false, the test is skipped and the test method body does not run.Final Answer:
Test skipped, no output -> Option BQuick Check:
False condition skips test [OK]
- Expecting test to run despite false condition
- Thinking it causes errors
- Confusing with @Disabled
@EnabledIf:public class SampleTest {
@Test
@EnabledIf("checkCondition")
void testSomething() {}
boolean checkCondition() { return true; }
}Solution
Step 1: Check method signature requirements
The method used in @EnabledIf must be static because JUnit calls it without instance.Step 2: Verify method return type and visibility
Return type boolean is correct and method visibility can be default or public, but static is mandatory.Final Answer:
checkCondition method must be static -> Option CQuick Check:
Condition method must be static [OK]
- Making condition method non-static
- Expecting expression attribute in @EnabledIf
- Confusing return type requirements
env equals prod and a static method isReady() returns true. Which @EnabledIf expression correctly combines these conditions?Solution
Step 1: Understand string comparison in Java expressions
Use'prod'.equals(System.getProperty('env'))to avoid NullPointerException if property is null.Step 2: Combine conditions with logical AND
Use&&to combine boolean expressions correctly in the string.Step 3: Validate syntax of @EnabledIf
The expression is passed as a single string without attribute name; @EnabledIf("'prod'.equals(System.getProperty('env')) && isReady()") matches this.Final Answer:
@EnabledIf("'prod'.equals(System.getProperty('env')) && isReady()") -> Option DQuick Check:
Use safe equals and && in string expression [OK]
- Using == for string comparison
- Using single & instead of &&
- Adding expression attribute which is invalid
Ready to prove it?
Pass the test and this pattern moves unknown
