【发布时间】:2020-06-19 09:48:16
【问题描述】:
在我的 JUNIT5 测试中,我想通过 @MockBean 模拟一个 bean。在我的 @BeforeEach - 方法中,调用被注入。 但是其他bean @Autowire-ing @MockBean 在方法注入之前用@MockBean 实例化。这很奇怪,给了我 NPE。如何在使用 @MockBean 之前强制方法注入?
@SpringBootTest
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:context/authenticationStaff.xml")
@EnableAutoConfiguration
public class PasswordPolicyServiceTest {
private final List<Reference> bcryptDigestRefs = new ArrayList<>();
private final DigestHistoryRule bcryptDigestRule = new DigestHistoryRule(new BCryptHashBean());
@MockBean
private SystemConfiguration systemConfiguration;
@BeforeEach
public void initMock() {
MockitoAnnotations.initMocks(this);
Arrays.asList(SystemConfigKey.values()).forEach(key -> {
Mockito.when(systemConfiguration.getConfig(key)).thenReturn(getConfig(key, key.getDefaultValue()));
});
Mockito.when(systemConfiguration.getConfig(SystemConfigKey.MIN_PASSWORD_LENGTH)).thenReturn(getConfig(SystemConfigKey.MIN_PASSWORD_LENGTH, "5"));
失败的课程是:
@Service
public class SessionCacheManager {
private final Ehcache ehCache;
private final Cache<String, SessionVerificationType> sessionCache;
private final SystemConfiguration systemConfiguration;
@Autowired
public SessionCacheManager(final Ehcache ehCache, final SystemConfiguration systemConfiguration) {
this.ehCache=ehCache;
this.systemConfiguration=systemConfiguration;
SystemConfigType systemConfig = systemConfiguration.getConfig(SystemConfigKey.SESSION_MAX_NUMBER);
Integer numberOfParalledSessions = systemConfig.getIntegerValue();
CacheManager cacheManager=ehCache.registerNewCacheManager(CACHE_MANAGER);
sessionCache = cacheManager.createCache(CACHE_NAME,
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, SessionVerificationType.class, ResourcePoolsBuilder.heap(numberOfParalledSessions)));
}
正如我所见(通过调试),“SessionCacheManager”使用模拟的“SystemConfiguration”,但 systemConfiguration.getConfig(SystemConfigKey.SESSION_MAX_NUMBER);返回一个空值。
【问题讨论】:
标签: spring-boot mockito junit5