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
相关产品推荐
相关产品推荐

