SpringBootTest 测试的一个问题

2019-12-31 09:49:30 +08:00
 b0644170fc

我的工程是个 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) 没有起作用. 大佬看下这是为什么?

3173 次点击
所在节点    Java
3 条回复
zhazi
2020-01-01 01:44:03 +08:00
你点进注解去看看注释就明白了
b0644170fc
2020-01-02 23:58:43 +08:00
@zhazi 你是说哪个注解? @SpringBootTest 的注解吗?我看了, @SpringBootTest(classes = CouponTplServiceImplTestApplication.class)的目的就是为了加载一个 ApplicationContext 的吧?
b0644170fc
2020-01-09 14:43:01 +08:00
我现在知道原因了.是因为我用于测试的制定类上有个 @ComponentScan("..."),这里写的路径,会把项目中的启动类也扫描进来,因此,最终会读取到总的 [spring/spring-context.xml] 这个文件.解决办法就是去掉 @ComponentScan("...")这个注解

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/633782

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX