JUnit测试中@Value注入属性值为null的问题排查
JUnit测试中@Value无法从application-test.yml注入属性的解决办法
你的问题核心在于测试类同时使用了@SpringBootTest和@ExtendWith(MockitoExtension.class):MockitoExtension是用于纯Mock场景的测试扩展,它不会启动Spring上下文,导致@Value这类依赖注入注解完全没被Spring处理,所以你的serviceAccountUser和pathFile始终为null。而@SpringBootTest本身已经集成了SpringExtension,足以支持Spring上下文加载与依赖注入,不需要额外引入Mockito的扩展。
解决步骤
- 移除
@ExtendWith(MockitoExtension.class)注解 - 如果测试中需要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
相关产品推荐
相关产品推荐

