@EnabledIfSystemProperty in JUnit - Build an Automation Script
import org.junit.jupiter.api.*; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import static org.junit.jupiter.api.Assertions.assertTrue; public class EnabledIfSystemPropertyTest { @BeforeEach void clearProperty() { System.clearProperty("env"); } @Test @EnabledIfSystemProperty(named = "env", matches = "test") void testRunsOnlyIfEnvIsTest() { // This test runs only if system property 'env' equals 'test' String env = System.getProperty("env"); assertTrue("test".equals(env), "System property 'env' should be 'test'"); } @Test void testAlwaysRuns() { // Control test to show normal test execution assertTrue(true); } public static void main(String[] args) { // Example to run tests with system property set System.setProperty("env", "test"); org.junit.platform.launcher.LauncherDiscoveryRequest request = org.junit.platform.engine.discovery.DiscoverySelectors.selectClass(EnabledIfSystemPropertyTest.class); // Normally tests run via IDE or build tool } }
The test class EnabledIfSystemPropertyTest contains a test method testRunsOnlyIfEnvIsTest annotated with @EnabledIfSystemProperty. This annotation makes the test run only if the system property named env matches the value test.
Before each test, the system property env is cleared to avoid side effects. To run the conditional test, set the system property env to test before running the tests.
The assertion inside the test confirms that the system property is indeed test when the test runs.
Another test testAlwaysRuns is included to show a normal test that always runs.
This setup helps beginners understand how to use @EnabledIfSystemProperty to conditionally run tests based on environment settings.
Now add data-driven testing with 3 different system property values ('test', 'dev', 'prod') and verify which tests run.