1.問題描述
使用springboot test報(bào)錯(cuò):
Application run failed java.lang.NullPointerException: null at com.xx.BCondition.matches(BCondition.java:11)
ERROR [org.springframework.test.context.TestContextManager:250] - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@5f0fd5a0] to prepare test instance [com.xx.WorkerTest@52fc5eb1]
java.lang.IllegalStateException: Failed to load ApplicationContext
2.原因
項(xiàng)目中采用@Conditional注解決定啟動(dòng)后注入哪個(gè)類(AWorker或者BWorker翻屈,他們都是AbstractWorker 的子類)齐饮,采用了傳參的方式來決定谓媒,該類會(huì)在實(shí)例化后進(jìn)行一些項(xiàng)目初始化操作必孤,而Test類中沒有傳參
@Configuration
public class WorkerClassConfig {
@Bean
@Conditional(ACondition.class)
public AbstractWorker getAWorker() {
return new AWorker();
}
@Bean
@Conditional(BCondition.class)
public AbstractWorker getBWorker() {
return new BWorker();
}
}
public class ACondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return conditionContext.getEnvironment().getProperty("workerClassName").contains("A");
}
}
public class BCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return conditionContext.getEnvironment().getProperty("workerClassName").contains("B");
}
}
3.解決
在測(cè)試類@SpringBootTest注解加上參數(shù):
@SpringBootTest(properties = "workerClassName=A")