V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
b0644170fc
V2EX  ›  Java

SpringBootTest 测试的一个问题

  •  
  •   b0644170fc · 2019-12-31 09:49:30 +08:00 · 3159 次点击
    这是一个创建于 1549 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    3 条回复    2020-01-09 14:43:01 +08:00
    zhazi
        1
    zhazi  
       2020-01-01 01:44:03 +08:00 via Android
    你点进注解去看看注释就明白了
    b0644170fc
        2
    b0644170fc  
    OP
       2020-01-02 23:58:43 +08:00
    @zhazi 你是说哪个注解? @SpringBootTest 的注解吗?我看了, @SpringBootTest(classes = CouponTplServiceImplTestApplication.class)的目的就是为了加载一个 ApplicationContext 的吧?
    b0644170fc
        3
    b0644170fc  
    OP
       2020-01-09 14:43:01 +08:00
    我现在知道原因了.是因为我用于测试的制定类上有个 @ComponentScan("..."),这里写的路径,会把项目中的启动类也扫描进来,因此,最终会读取到总的 [spring/spring-context.xml] 这个文件.解决办法就是去掉 @ComponentScan("...")这个注解
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3261 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:44 · PVG 19:44 · LAX 04:44 · JFK 07:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.