javaspringjunit

@DisabledIf with jUnit depending on a string value in application.yml


I need to disable some unit tests depending on a string variable defined in my src/app/test/resources/application.yml.

ENVIRONMENT: local

I'm using Spring's @DisabledIf which takes a single expression. But I can't make it work when an expression is a string evaluation that I'm trying to fit into SpEL.

@Test
@DisabledIf(expression="${ENVIRONMENT == 'local'}") 
public void test1() throws Exception {
    //..
}

Also tried, not working (unit test still activates even with ENVIRONMENT: local):

@DisabledIf("#{ '${ENVIRONMENT}' == 'local' }") // String comparison

Their examples are

@DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
@DisabledIf("${smoke.tests.disabled}") <- A boolean application.yml property
@DisabledIf("true")

I need a Spring environment property from application.yml but with string evaluation, what would work here?

BTW the following doesn't work either with my application.yml variable, using JUnit's Jupiter:

@DisabledIfSystemProperty(named="ENVIRONMENT", matches="local")

Solution

  • You just need to tell Spring to load the context so it can read from application.yml using the loadContext attribute of DisabledIf annotation:

    @DisabledIf(value = "#{'${ENVIRONMENT}' == 'local'}", loadContext = true) // loadContext = true added
    @Test
    void test() {
    
    }
    

    From the javadoc of the loadContext attribute in the DisabledIf annotation:

    Whether the ApplicationContext associated with the current test should be eagerly loaded in order to evaluate the expression. Defaults to false so that test application contexts are not eagerly loaded unnecessarily. If an expression is based solely on system properties or environment variables or does not interact with beans in the test's application context, there is no need to load the context prematurely since doing so would be a waste of time if the test ends up being disabled.