...

/

Environment Variable Conditions - @DisabledIfEnvironmentVariable and @EnabledIfEnvironmentVariable

Environment Variable Conditions - @DisabledIfEnvironmentVariable and @EnabledIfEnvironmentVariable

This lesson demonstrates how to disable or enable test methods or a complete test class using Environment variable conditions.

@DisabledIfEnvironmentVariable and @EnabledIfEnvironmentVariable

Junit 5 helps us to disable or enable test cases using various conditions. JUnit Jupiter API provides annotations in org.junit.jupiter.api.condition package to enable/disable tests based on a certain condition. The annotations provided by API can be applied to test methods as well as the class itself. The two annotations which use system environment properties and specified regex to disable or enable tests are - @DisabledIfEnvironmentVariable and @EnabledIfEnvironmentVariable. Let’s take a look at a demo.

package com.hubberspot.junit5.disabled;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
public class DisabledIfEnvironmentVariableTest {
@Test
void testOnAllEnvironmentVariables() {
assertTrue(3 > 0);
}
@DisabledIfEnvironmentVariable(named="USER", matches="dinesh")
@Test
void testDisabledIfUserMatchesDinesh() {
assertFalse(0 > 4);
}
@DisabledIfEnvironmentVariable(named="HOME", matches="/dummies/home")
@Test
void testDisabledIfHomeMatchesDummyDirectory() {
assertFalse(10 > 40);
}
}
widget

Above test program has 3 test methods and @DisabledIfEnvironmentVariable is applied on 2 test methods as.

  1. testDisabledIfUserMatchesDinesh() -
...