0
0
JUnittesting~5 mins

@EnabledIfEnvironmentVariable in JUnit

Choose your learning style9 modes available
Introduction

This annotation helps run tests only when a specific environment variable has a certain value. It avoids running tests in the wrong setup.

You want to run a test only on a developer's machine with a special setup.
You want to skip tests on a production server where environment variables differ.
You want to test features that depend on external services enabled by environment variables.
You want to avoid running slow tests unless a flag is set in the environment.
Syntax
JUnit
@EnabledIfEnvironmentVariable(named = "ENV_VAR_NAME", matches = "expectedValue")

The named attribute is the environment variable name to check.

The matches attribute is a regular expression to match the variable's value.

Examples
This test runs only if the environment variable ENV equals dev.
JUnit
@EnabledIfEnvironmentVariable(named = "ENV", matches = "dev")
void testOnlyOnDev() {
    // test code
}
This test runs only if RUN_SLOW_TESTS is set to true.
JUnit
@EnabledIfEnvironmentVariable(named = "RUN_SLOW_TESTS", matches = "true")
void slowTest() {
    // slow test code
}
Sample Program

The first test runs only if the environment variable TEST_MODE is set to enabled. The second test runs always.

JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;

public class EnvVarTest {

    @Test
    @EnabledIfEnvironmentVariable(named = "TEST_MODE", matches = "enabled")
    void testRunsOnlyIfEnvVarSet() {
        System.out.println("Test is running because TEST_MODE=enabled");
    }

    @Test
    void testAlwaysRuns() {
        System.out.println("This test always runs");
    }
}
OutputSuccess
Important Notes

If the environment variable is not set or does not match, the test is skipped, not failed.

Use this to control tests in different environments without changing code.

Summary

@EnabledIfEnvironmentVariable runs tests only when an environment variable matches a value.

It helps run or skip tests based on the environment setup.

Use it to avoid running tests in wrong or unsupported environments.