SpringBootTest 测试的一个问题
資深大佬 : b0644170fc 48
我的工程是个 maven 管理的 springboot 项目,有个启动类如下
@EnableApolloConfig @SpringBootApplication @PropertySource @EnableSwagger2 @EnableScheduling @ImportResource({"classpath:spring/spring-context.xml"}) public class CouponApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(CouponApplication.class); } }
@ImportResource 导入了 spring-context.xml 文件,这是总的 xml 文件,里面导入年其它 xml 文件
我现在想要测试,我自己又创建了一个启动类如下:
@SpringBootApplication @ImportResource("classpath:spring/spring-datasource.xml") @ComponentScan("...") @EnableApolloConfig({"jdbc", "config"}) @Import({BeanConfig.class, DataSourceConfig.class, RedisConfig.class}) @OverrideAutoConfiguration(enabled = false) public class CouponTplServiceImplTestApplication { }
@ImportResource 中只导入了和数据库相关的 xml.
以下是我的测试类
@SpringBootTest(classes = CouponTplServiceImplTestApplication.class) @RunWith(SpringRunner.class) @MockBean({HttpClientUtils.class, AppInstanceRpc.class}) public class CouponTplServiceImplTest {}
我在测试类里制定的启动类是我自己创建的启动类,并不是项目中的.因此,启动类要加载的 xml 文件应该是 spring/spring-datasource.xml.但实际情况却不是.启动测试的时候,报错如下:
Caused by: java.io.FileNotFoundException: class path resource [spring/spring-context.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330) ... 45 more
错误中能看到 FileNotFoundException: class path resource [spring/spring-context.xml] . 这是因为我故意把 resouces/spring/ 目录下的其它 xml 给移除了. 从结果看,好像是 @SpringBootTest(classes = CouponTplServiceImplTestApplication.class) 没有起作用. 大佬看下这是为什么?
大佬有話說 (2)