You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试时@Value注解无法读取yml配置文件值该如何解决?

问题根源

@Value注解是Spring提供的依赖注入特性,只有当前类是由Spring容器管理的Bean时才会生效。你测试时没有加载Spring上下文,要么是直接手动实例化了GrpcAuthorizationInterceptor类,要么测试类没有加载配置文件,导致两个字段为null。


解决方案

方案1:测试加载Spring上下文(集成测试场景)

如果是需要验证完整Bean初始化逻辑的集成测试,按以下配置修改:

  • 测试类添加@SpringBootTest注解,自动扫描加载主/测试资源目录下的application.yml配置
  • 测试类中通过@Autowired注入GrpcAuthorizationInterceptor实例,禁止手动new对象
  • 若仅需要加载配置、不想启动全量Spring容器,可在测试类添加注解:
@ContextConfiguration(classes = GrpcAuthorizationInterceptor.class)
@TestPropertySource(locations = "classpath:application.yml")

方案2:纯单元测试不启动Spring上下文

如果是只测试业务逻辑的单测,不需要依赖Spring容器,直接手动给字段赋值即可:
使用Spring提供的ReflectionTestUtils工具类快速赋值:

GrpcAuthorizationInterceptor interceptor = new GrpcAuthorizationInterceptor();
ReflectionTestUtils.setField(interceptor, "clientId", "1234");
ReflectionTestUtils.setField(interceptor, "clientSecret", "1234");

注意事项

确认测试资源目录src/test/resources下存在对应yml配置文件,若仅src/main/resources下有配置、测试目录没有,也会出现读取不到的问题。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:39:03