JUnit5单元测试无法读取application-test.yml配置属性问题求助
问题核心原因
你遇到的配置不生效问题有两个核心诱因:
@TestPropertySource注解默认仅支持.properties和.xml格式的属性文件,不支持 YAML 格式解析,你指定的application-test.yml没有被正确加载。@TestPropertySource使用方式有误:spring.config.location是 Spring Boot 启动级的环境参数,不适合在该注解的properties属性中配置,指定外部配置文件应该用注解自带的locations属性。
可行解决方案
你可以根据自己的需求任选以下一种方案修复:
方案1:改用 properties 格式配置文件(改动最小)
把 application-test.yml 重命名为 application-test.properties,内容调整为 properties 格式:
prefix.aValue=1 prefix.aList[0]=a prefix.aList[1]=b prefix.aList[2]=c
然后修改测试类的@TestPropertySource注解:
@TestPropertySource(locations = "classpath:application-test.properties")
无需其他改动,直接运行测试就能读到正确的配置值。
方案2:自定义属性源工厂支持 YAML 加载
如果你需要保留 YAML 格式的配置文件,先实现一个支持 YAML 解析的属性源工厂类:
import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.DefaultPropertySourceFactory; import org.springframework.core.io.support.EncodedResource; import java.io.IOException; import java.util.List; public class YamlPropertySourceFactory extends DefaultPropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()); return sources.get(0); } }
再修改测试类的@TestPropertySource注解,指定自定义工厂和配置文件位置:
@TestPropertySource( locations = "classpath:application-test.yml", factory = YamlPropertySourceFactory.class )
方案3:使用 Spring Boot 测试注解自动加载配置
如果是 Spring Boot 项目,直接使用@SpringBootTest配合激活 test 配置环境,不需要手动指定配置文件,更符合Spring Boot的约定:
@ExtendWith(SpringExtension.class) @SpringBootTest(classes = MyService.class) @EnableConfigurationProperties(MyConfigProperties.class) @ActiveProfiles("test") class MyServiceTest { @Autowired MyService myservice; @Test void testSth(){ // 原有测试逻辑不变 } }
Spring Boot 会自动扫描加载 classpath 下的 application-test.yml 配置文件。
内容的提问来源于stack exchange,提问作者asli
相关产品推荐
相关产品推荐

