Spring Boot读取外部YML配置属性的切片测试不生效如何解决
问题原因
你在@SpringBootTest中指定classes = {MyExternalConfProp.class}时,Spring测试上下文只会加载你显式指定的这一个类,缺少配置属性绑定所需的核心能力:
- 未限定classes的全量
@SpringBootTest会自动加载项目启动类,启动类上的@SpringBootApplication注解默认包含@EnableConfigurationProperties功能,会自动触发@ConfigurationProperties的配置绑定逻辑,同时也能正确识别你自定义的YamlPropertySourceFactory,完成外部yml文件的读取。 - 限定classes后,上下文没有启用配置绑定相关的处理器,也无法正确处理
@PropertySource注解加载yml文件,所以属性值注入为null。
解决方法
方案1:使用配置属性专用切片测试注解(推荐)
Spring Boot提供了专门的@ConfigurationPropertiesTest注解用于测试配置属性类,自动内置配置绑定能力,无需加载全量上下文,性能更高。修改测试类代码如下:
@ConfigurationPropertiesTest(MyExternalConfProp.class) class MyExternalConfPropTest { @Autowired private MyExternalConfProp confProp; @Test void externalConfigurationPropertyShouldBeLoadedIntoSpringContext() { assertThat(confProp).hasFieldOrPropertyWithValue("property", "yeyeye"); } }
方案2:给原有测试补充必要注解
如果你需要沿用@SpringBootTest的限定类写法,只需补充开启配置绑定的注解即可:
@SpringBootTest(classes = {MyExternalConfProp.class}) @EnableConfigurationProperties class MyExternalConfPropTest { @Autowired private MyExternalConfProp confProp; @Test void externalConfigurationPropertyShouldBeLoadedIntoSpringContext() { assertThat(confProp).hasFieldOrPropertyWithValue("property", "yeyeye"); } }
如果补充上述注解后仍不生效,可将自定义的yml读取工厂也加入加载类列表:
@SpringBootTest(classes = {MyExternalConfProp.class, YamlPropertySourceFactory.class}) @EnableConfigurationProperties class MyExternalConfPropTest { // 测试逻辑保持不变 }
内容的提问来源于stack exchange,提问作者riccardo.cardin
相关产品推荐
相关产品推荐

