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

Spring Boot 3.4+JUnit 5+Mockito:无法加载application-test.yml配置属性

Mockito测试中配置属性加载为null的问题及解决

我在使用Mockito编写服务层测试时,遇到了一个问题:需要从application-test.yml加载配置属性,这些属性在仓库测试中能正常读取,但在Mockito测试里却全部为null。

测试类代码

@ExtendWith(MockitoExtension.class)
@SpringJUnitConfig(classes = SecurityAppConfig.class)
@TestPropertySource(locations = "classpath:application-test.yml")
class AuthenticationServiceTest {

    @Mock
    private UserRepository userRepository;

    @Mock
    private PasswordEncoder passwordEncoder;

    @Mock
    private JwtServiceImpl jwtService;

    @Mock
    private AuthenticationManager authenticationManager;

    @InjectMocks
    private AuthenticationServiceImpl authenticationService;

    @Autowired
    private SecurityAppConfig securityAppConfig;

    @Test
    void shouldRegisterUser() throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidKeySpecException, BadPaddingException, InvalidKeyException {
        String hashKey = securityAppConfig.getHashKey();
    }

    @Test
    void authenticateUser() {
    }
}

配置类代码

@Configuration
@ConfigurationProperties(prefix = "app-config.security")
public class SecurityAppConfig {
//    @Value("${appConfig.security.aesKey}")
    private String aesKey;
//    @Value("${appConfig.security.aesSalt}")
    private String aesSalt;
//    @Value("${appConfig.security.hashKey}")
    private String hashKey;

    public String getAesKey() {
        return aesKey;
    }

    public void setAesKey(String aesKey) {
        this.aesKey = aesKey;
    }

    public String getAesSalt() {
        return aesSalt;
    }

    public void setAesSalt(String aesSalt) {
        this.aesSalt = aesSalt;
    }

    public String getHashKey() {
        return hashKey;
    }

    public void setHashKey(String hashKey) {
        this.hashKey = hashKey;
    }
}

解决办法

原本不清楚问题出在哪,后来通过给测试类添加以下注解,成功解决了属性加载为null的问题:

@EnableConfigurationProperties
@ContextConfiguration(classes = AppSecurityConfig.class)
@Extensions({
        @ExtendWith(MockitoExtension.class),
        @ExtendWith(SpringExtension.class)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:13:26