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

JUnit测试中@Value注入属性值为null的问题排查

JUnit测试中@Value无法从application-test.yml注入属性的解决办法

你的问题核心在于测试类同时使用了@SpringBootTest和@ExtendWith(MockitoExtension.class):MockitoExtension是用于纯Mock场景的测试扩展,它不会启动Spring上下文,导致@Value这类依赖注入注解完全没被Spring处理,所以你的serviceAccountUser和pathFile始终为null。而@SpringBootTest本身已经集成了SpringExtension,足以支持Spring上下文加载与依赖注入,不需要额外引入Mockito的扩展。

解决步骤

  1. 移除@ExtendWith(MockitoExtension.class)注解
  2. 如果测试中需要Mock某些依赖Bean,直接使用Spring Boot提供的@MockBean注解替代

修改后的测试类代码:

@SpringBootTest
@ActiveProfiles("test")
public class GoogleServiceUtilsTest {
    @Value("${google.service.account.user}")
    private String serviceAccountUser;

    @Value("${google.service.account.path}")
    private String pathFile;

    Set<String> scopesSet = DirectoryScopes.all();
    List<String> scopesList = new ArrayList<String>(scopesSet);

    // 若需Mock依赖Bean,用@MockBean标注即可
    // @MockBean
    // private YourDependency yourDependency;

    @Test
    void getCredentialTest() throws GoogleCredentialException {
        // Given
        GoogleCredentials credentials;

        // When
        credentials = GoogleServiceUtils.getCredential(serviceAccountUser, scopesList, pathFile);

        // Then
        assertThat(credentials).isNotNull();
        assertThat(new HttpCredentialsAdapter(credentials)).isNotNull();
    }
}

额外验证点

  • 确认application-test.yml的路径和命名完全正确:src/test/resources/application-test.yml
  • 检查YAML文件的缩进格式(YAML对缩进敏感,确保google下的层级缩进一致且正确)
  • 若仍有问题,可以尝试在测试类上添加@ConfigurationPropertiesScan注解,确保配置属性被正确扫描

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:40:24