0
0
JUnittesting~15 mins

@EnabledIfEnvironmentVariable in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify test execution only when environment variable is set
Preconditions (1)
Step 1: Check the environment variable TEST_ENV value
Step 2: If TEST_ENV is 'true', run the test method
Step 3: If TEST_ENV is not 'true', skip the test method
Step 4: Inside the test method, assert that 2 + 2 equals 4
✅ Expected Result: The test runs and passes only if TEST_ENV is 'true'. Otherwise, the test is skipped.
Automation Requirements - JUnit 5
Assertions Needed:
Assert that 2 + 2 equals 4
Best Practices:
Use @EnabledIfEnvironmentVariable annotation to conditionally enable test
Use Assertions.assertEquals for validation
Keep test method simple and focused
Include clear test method name describing the condition
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class EnvironmentVariableTest {

    @Test
    @EnabledIfEnvironmentVariable(named = "TEST_ENV", matches = "true")
    void testRunsOnlyIfEnvVarIsTrue() {
        assertEquals(4, 2 + 2, "2 + 2 should equal 4");
    }
}

This test class uses JUnit 5's @EnabledIfEnvironmentVariable annotation to run the test method only when the environment variable TEST_ENV is set to the string "true".

The test method testRunsOnlyIfEnvVarIsTrue asserts that 2 + 2 equals 4 using assertEquals. If the environment variable does not match, JUnit will skip this test automatically.

This approach keeps the test simple and clear, and uses JUnit's built-in conditional test execution feature.

Common Mistakes - 4 Pitfalls
Using @EnabledIfEnvironmentVariable with incorrect environment variable name
Using @EnabledIfEnvironmentVariable with a wrong regex pattern in matches attribute
Not setting the environment variable before running the test
Using @EnabledIfEnvironmentVariable on a class without understanding it applies to all tests
Bonus Challenge

Now add two more test methods that run only when TEST_ENV is 'false' and when TEST_ENV is unset, respectively.

Show Hint