Springboot单元测试无法读取配置文件的解决方案

单元测试无法读取配置文件

首先,测试类要加注解

表示该类是一个测试类,默认会加载resource文件夹下的配置文件。

Springboot单元测试无法读取配置文件的解决方案_第1张图片

如果想要指定配置文件:

 
@TestPropertySource("classpath:pay.properties")

深渊巨坑

spring boot 2,在进行单元测试的时候,不支持.yml文件!!!至文章日期,还未解决。

用yml文件的小伙伴别折腾了,测试文件夹下放一个properties文件吧!

单元测试加载配置文件启动异常

报错内容:Failed to load ApplicationContext

Invalid bean definition with name 'dataSource' defined in URL [file:/D:/KaiFa/pals/IBC/target/classes/spring-mybatis.xml]: Could not resolve placeholder 'jdbc.driver' in string value "${jdbc.driver}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.driver' in string value "${jdbc.driver}"

Could not resolve placeholder 'jdbc.driver' in string value "${jdbc.driver}"

贴一些关键错误,就不全贴了.错误说的在单元测试加载配置文件的时候无法加载jdbc.properties中的配置参数

最初以为是配置文件路径写错了

经过排查后没有问题

检查了引包  spring-test的版本是4.0.2.RELEASE


    junit
    junit
    4.12


    org.springframework
    spring-test
    ${spring.version}

这是单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/spring-mvc.xml","classpath*:/spring-mybatis.xml"})
public class BaseDao {
    @Resource
    private HomeXmlService homeXmlService;
    @Test
    public void csh() {
        HomeDao c = new HomeDao();
        homeXmlService.setXmlData(c);
    }
}

最后确认是因为xml配置问题

在单元测试加载了spring-mvc和spring-mybatis两个文件

在两个配置中我分别加载了Properties配置文件。

spring-mybatis.xml


   

spring-mvc.xml


   
      
         classpath:prop/url.properties
         classpath:prop/synthetic-ratio.properties
      
   

经过不断排查和发现是因为分别引用了properties的问题

后因为是spring-mybatis报错,就在家在配置中加入

调试后发现仍然有问题

最终确认,不止spring-mybaits,spring-mvc也要加这句,配置属性的字面意思就是忽略不肯舍弃的占位符

问题解决。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的:(Springboot单元测试无法读取配置文件的解决方案)