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

单元测试中使用@TestPropertySource时@Value变量始终为NULL

解决Spring Boot单元测试@Value属性注入为NULL的问题

问题根源

你的测试类存在三个关键配置错误:

  • 注解冲突:同时使用@RunWith(SpringJUnit4ClassRunner.class)和@ExtendWith(MockitoExtension.class),干扰了Spring上下文初始化流程,导致属性注入失效。
  • @TestPropertySource用法错误:
    • 内联属性的键值对不能添加空格(比如eligible_filename = xyz里的空格会让键变为eligible_filename ,与@Value中指定的键不匹配)。
    • 加载YAML文件不能使用properties属性,该属性用于定义内联键值对;加载文件需用locations,且Spring Boot原生TestPropertySource不直接支持YAML,用profile方式更简洁可靠。
  • 缺少Spring Boot测试启动注解:单独使用@SpringBootConfiguration不足以启动完整的测试上下文,必须用@SpringBootTest触发自动配置和属性加载机制。

解决办法

方法1:内联属性快速测试

用@SpringBootTest启动测试上下文,配合@TestPropertySource指定内联属性(注意去掉等号两边的空格):

@SpringBootTest
@TestPropertySource(properties = {
        "eligible_filename=xyz"
})
public class AppServiceTest {
    
    @Value("${eligible_filename}")
    private String eligibleFilename;
    
    // 测试逻辑代码...
}

方法2:加载YAML配置文件

  1. 先在src/test/resources/application-test.yaml中配置属性:
eligible_filename: xyz
  1. 测试类激活test环境,自动加载对应YAML文件:
@SpringBootTest
@ActiveProfiles("test")
public class AppServiceTest {
    
    @Value("${eligible_filename}")
    private String eligibleFilename;
    
    // 测试逻辑代码...
}

方法3:Mock依赖与属性注入共存

如果需要Mock其他依赖,不要混用JUnit4和Mockito的Runner/Extension,直接用@SpringBootTest配合@MockBean注入Mock对象:

@SpringBootTest
@TestPropertySource(properties = {"eligible_filename=xyz"})
public class AppServiceTest {
    
    @Value("${eligible_filename}")
    private String eligibleFilename;
    
    @MockBean
    private YourDependency yourDependency;
    
    // 测试逻辑代码...
}

额外检查点

  • 确保@Value标注的变量不是private static或final类型。
  • 确认YAML文件放在src/test/resources目录下,文件名拼写正确(比如application-test.yaml)。
  • 使用JUnit5时,直接用@SpringBootTest即可,它已包含@ExtendWith(SpringExtension.class),无需额外添加@RunWith注解。

内容的提问来源于stack exchange,提问作者gene b.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:33:02