1

I'm writing unit tests and trying to use ExecutionCondition for enabling the test only when specific profile activated exclusively.

I created my ExecutionCondition.

class EnabledWithH2ExclusiveExecutionCondition implements ExecutionCondition {

    @Override
    public ConditionEvaluationResult evaluateExecutionCondition(
            final ExtensionContext context) {
        // check the environment
    }

    @Autowired
    private Environment environment;
}

But the environment is not injected.

How can I do that?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

4

Because your ExecutionCondition is created by JUnit5 itself using reflection .It is not managed by Spring and so the @Autowired will not work.

You can call SpringExtension.getApplicationContext() to get Spring Context and then get the Environment from it :

@Override
public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context){
          Environment env = SpringExtension.getApplicationContext(context).getEnvironment();
        // check the environment
}
Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • That's partially true, and that approach of course works. Note, however, that one may alternatively choose the approach mentioned here: https://stackoverflow.com/questions/50237046/junit-5-inject-spring-components-to-custom-testtemplateinvocationcontextprovide – Sam Brannen Jan 22 '19 at 13:02
  • Thanks for the info, didn't know that before – Ken Chan Jan 22 '19 at 16:12