0
0
JUnittesting~10 mins

@EnabledIfEnvironmentVariable in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if a feature runs only when a specific environment variable is set to a certain value. It verifies conditional test execution based on environment settings.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class EnvVariableTest {

    @Test
    @EnabledIfEnvironmentVariable(named = "RUN_FEATURE", matches = "true")
    void testFeatureRunsOnlyIfEnvVarIsTrue() {
        // Simulate feature logic
        boolean featureActive = true;
        assertTrue(featureActive, "Feature should be active when RUN_FEATURE=true");
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test runner starts and checks environment variable RUN_FEATUREEnvironment variable RUN_FEATURE is set to 'true'-PASS
2JUnit detects @EnabledIfEnvironmentVariable condition is met and runs testFeatureRunsOnlyIfEnvVarIsTrue()Test method is executing-PASS
3Inside test, assertTrue(featureActive) is calledfeatureActive is trueassertTrue(featureActive) verifies featureActive is truePASS
4Test completes successfullyTest passed-PASS
Failure Scenario
Failing Condition: Environment variable RUN_FEATURE is not set to 'true' or is missing
Execution Trace Quiz - 3 Questions
Test your understanding
What causes the test to run in this example?
ANo environment variable is needed
BRUN_FEATURE environment variable is set to 'false'
CRUN_FEATURE environment variable is set to 'true'
DTest always runs regardless of environment
Key Result
Use @EnabledIfEnvironmentVariable to run tests only when specific environment variables are set, helping control test execution in different environments.