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.
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.
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"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and checks environment variable RUN_FEATURE | Environment variable RUN_FEATURE is set to 'true' | — | PASS |
| 2 | JUnit detects @EnabledIfEnvironmentVariable condition is met and runs testFeatureRunsOnlyIfEnvVarIsTrue() | Test method is executing | — | PASS |
| 3 | Inside test, assertTrue(featureActive) is called | featureActive is true | assertTrue(featureActive) verifies featureActive is true | PASS |
| 4 | Test completes successfully | Test passed | — | PASS |
@EnabledIfEnvironmentVariable annotation in JUnit?ENV equals prod using @EnabledIfEnvironmentVariable?named for the environment variable name and matches for the expected value.named = "ENV" and matches = "prod".MODE is set to test?
@EnabledIfEnvironmentVariable(named = "MODE", matches = "prod")
void runOnlyInProd() {
System.out.println("Running in prod mode");
}MODE is set to test, but the annotation requires prod.@EnabledIfEnvironmentVariable:
@EnabledIfEnvironmentVariable(named = "APP_ENV", match = "dev")
void testInDev() {
// test code
}matches, not match.DEPLOY_ENV is set to either staging or production. How can you achieve this using @EnabledIfEnvironmentVariable in JUnit?matches attribute supports regular expressions to match multiple values.staging|production matches either value in one annotation.Pass the test and this pattern moves unknown