Verify test execution only when environment variable is set
Preconditions (1)
✅ Expected Result: The test runs and passes only if TEST_ENV is 'true'. Otherwise, the test is skipped.
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.
Now add two more test methods that run only when TEST_ENV is 'false' and when TEST_ENV is unset, respectively.
@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