Java 运行测试时排除SpringApplicationRunListener
我使用了一个库来实现SpringApplicationRunListener类Java 运行测试时排除SpringApplicationRunListener,java,spring,spring-boot,Java,Spring,Spring Boot,我使用了一个库来实现SpringApplicationRunListener类 public class FromLibApplicationRunListener implements SpringApplicationRunListener {...} 这个库在运行测试时加载了很多我不想要的东西。所以我尝试创建一个测试应用程序 @SpringBooApplication @ComponentScan(excudeFilters = @ComponentScan.Filters(type=
public class FromLibApplicationRunListener implements SpringApplicationRunListener {...}
这个库在运行测试时加载了很多我不想要的东西。所以我尝试创建一个测试应用程序
@SpringBooApplication
@ComponentScan(excudeFilters = @ComponentScan.Filters(type= ASSIGNABLE_TYPE,
value={RealApp.java, FromLibApplicatioRunListener})
public class TestApp {
public static main(String[] args) {
SpringApplication.run(TestApp.class ,args);
}
}
但当我运行TestApp时,它仍然抛出异常
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.....FromLibApplicationRunListner]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184)
at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:435)
... 6 more
运行测试时如何删除此库?您可以使用配置文件:
@Profile(“!test”)
libApplicationRunListener的公共类实现SpringApplicationRunListener{…}
。。。
@ActiveProfiles(“测试”)
公共类MyTest{
或在application.yaml
文件(或application.properties
)中设置应用程序活动配置文件
另一种解决方案是在测试配置中重写bean:
@SpringBootTest(classes=MyTest.TestConfig.class)
类MyTest{
@测试配置
静态类TestConfig{
@豆子
public FromLibApplicationRunListener侦听器存根(){
从libapplicationrunlistener()返回新的{
//重写此处使用的SpringApplicationRunListener方法
};
}
}
...
}
或
@SpringBootTest(classes=MyTest.TestConfig.class)
类MyTest{
@测试配置
静态类TestConfig{
@豆子
公共SpringApplicationRunListener fromLibApplicationRunListener(){
返回新的SpringApplicationRunListener(){};
}
}
...
}
我无法将代码添加到FromLibApplicationRunListener,因为它来自外部lib。在这种情况下,您可以在测试配置中覆盖FromLibApplicationRunListener
bean。当我从Spring读取代码时,它将使用类加载器,从SpringApplicationRunListener加载所有类扩展。如果我从FromL创建类扩展iApplicationRunListener
,然后它将同时加载它们
spring:
profiles:
active: dev