我们在一个项目中使用了 Redis 缓存。我们已经实现了 Mockito,我们正在模拟存储库层,但 redisTemplate 被用于从服务层的缓存中获取数据,我们正在尝试模拟 RedisTemplate 但无法这样做
@MockBean
private RedisTemplate<Object, Object> redisTemplate;
@Test
public void testGetProductHappyPath() {
log.info(ApplicationConstantsTest.METHOD_ENTER_LABEL);
when(redisTemplate.keys(ArgumentMatchers.any())).thenReturn(null);
final RequestBuilder requestBuilder = MockMvcRequestBuilders.get(ApplicationConstantsTest.PRODUCT_WALLET_OF_PRODUCT, Integer.MAX_VALUE)
.accept(MediaType.APPLICATION_JSON);
try {
mockMvc.perform(requestBuilder).andExpect(status().isOk());
log.info(ApplicationConstantsTest.METHOD_EXIT_LABEL);
} catch (final Exception e) {
log.error(ApplicationConstantsTest.METHOD_EXCEPTION_LABEL, e);
}
}
但我们得到了这个:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.core.RedisKeyValueAdapter]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: ConnectionFactory must not be null!
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:217)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:309)
... 65 common frames omitted
Caused by: java.lang.IllegalArgumentException: ConnectionFactory must not be null!
at org.springframework.util.Assert.notNull(Assert.java:201)
at org.springframework.data.redis.listener.RedisMessageListenerContainer.setConnectionFactory(RedisMessageListenerContainer.java:311)
at org.springframework.data.redis.core.RedisKeyValueAdapter.initMessageListenerContainer(RedisKeyValueAdapter.java:712)
at org.springframework.data.redis.core.RedisKeyValueAdapter.<init>(RedisKeyValueAdapter.java:196)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204)