0
0
JUnittesting~5 mins

@EnabledIfSystemProperty in JUnit

Choose your learning style9 modes available
Introduction

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

Run tests only on a developer's machine with a special setup.
Skip tests when running on a continuous integration server.
Run tests only if a feature flag is enabled via system properties.
Avoid running tests on unsupported operating systems.
Control test execution based on environment variables passed as system properties.
Syntax
JUnit
@EnabledIfSystemProperty(named = "propertyName", matches = "valueRegex")

The named attribute specifies the system property key.

The matches attribute uses a regular expression to match the property value.

Examples
This test runs only if the system property env equals exactly dev.
JUnit
@EnabledIfSystemProperty(named = "env", matches = "dev")
void testOnlyOnDev() {
    // test code
}
This test runs only on Windows operating systems by matching the os.name property.
JUnit
@EnabledIfSystemProperty(named = "os.name", matches = ".*Windows.*")
void testOnlyOnWindows() {
    // test code
}
Sample Program

The first test runs only if the system property runSpecialTests is set to true. The second test always runs.

JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class SystemPropertyTest {

    @Test
    @EnabledIfSystemProperty(named = "runSpecialTests", matches = "true")
    void testRunsOnlyIfPropertyTrue() {
        assertTrue("true".equals(System.getProperty("runSpecialTests")));
    }

    @Test
    void testAlwaysRuns() {
        assertTrue(true);
    }
}
OutputSuccess
Important Notes

System properties can be set when running tests using JVM arguments like -DrunSpecialTests=true.

If the property is missing or does not match, the test is skipped, not failed.

This helps keep tests clean and environment-aware without manual checks inside test code.

Summary

@EnabledIfSystemProperty runs tests only when a system property matches a pattern.

It helps control test execution based on environment settings.

Use it to skip or run tests automatically depending on where and how tests run.