Is it possible to override @DisabledIfEnvironmentVariable in jUnit 5?

Viewed 309

I have a class of jUnit 5 tests that is not allowed to run in the main pipeline (for multiple reasons). In order to disabled those tests in the pipeline but work on a developer machine I introduced @DisabledIfEnvironmentVariable for the test class (and it works great):

@DisabledIfEnvironmentVariable(named = "USER", matches = "(.*jenkins.*|.*tomcat.*)")
@SpringBootTest(classes = {BigApplication.class}, webEnvironment = RANDOM_PORT)
class LongRunningApplicationTest { ... }

How can I override @DisabledIfEnvironmentVariable if I want to run the test class on an occasion?

I tried adding @EnabledIfEnvironmentVariable hoping that it will override @DisabledIfEnvironmentVariable annotation, therefore providing me with a convenient way to run the test in the pipeline on occasion:

@EnabledIfEnvironmentVariable(named = "applicationTest", matches = "true")
@DisabledIfEnvironmentVariable(named = "USER", matches = "(.*jenkins.*|.*tomcat.*)")
@SpringBootTest(classes = {BigApplication.class}, webEnvironment = RANDOM_PORT)
class LongRunningApplicationTest { ... }

However the above approach doesn't work. Is there a way to override @DisabledIf... ?

1 Answers

One solution is to introduce your own conditions using following annotations: @EnabledIf or @DisabledIf.

@EnabledIf("EnabledIfAnnotationUtils#shouldRun")
class ApplicationTest {

    @Test
    void renameMe() {
        assertThat(false).isTrue();
    }
}

Where EnabledIfAnnotationUtils - is external class (in case you have multiple tests under same condition) and #shouldRun - name of static method. Example:

public class EnabledIfAnnotationUtils {

    static boolean shouldRun() {
        boolean override = getPropertySafely("run-long-tests").equalsIgnoreCase("true");
        if(override) return true;

        String user = getEnvSafely("USER");
        boolean isOnJenkins = user.toLowerCase().contains("jenkins") || user.toLowerCase().contains("tomcat");

        return !isOnJenkins;
    }

    private static String getPropertySafely(String name) {
        return "" + System.getProperty(name);
    }

    private static String getEnvSafely(String name) {
        return "" + System.getenv(name);
    }
}

Now tests will NOT run on Jenkins unless override parameter passed, example:

mvn test -Drun-long-tests=true
Related