Mockito无法Mock RedisTemplate解决方案
如题,在SpringBoot工程中使用@MockBean对RedisTemplate进行Mock时发现报错,RedisTemplate连接工厂为null
当尝试将RedisConnectFaction注入测试类进行Mock后发现依然无效。
所以尝试新的解决方案:
将RedisTemplate使用@Spy注入原始类,在测试运行前对RedisTemplate底层方法进行批量Mock文章来源:https://www.toymoban.com/news/detail-519733.html
public class RedisTemplateMockUtil {
/**
* Resolve:RedisTemplate cannot use @ MockBean for Mock
* @param redisTemplate spy redis template
* @param key bound key
*/
public static void mockRedisTemplate(RedisTemplate<String,Object> redisTemplate,String key){
ValueOperations valueOperations = Mockito.mock(ValueOperations.class);
SetOperations setOperations = Mockito.mock(SetOperations.class);
HashOperations hashOperations = Mockito.mock(HashOperations.class);
ListOperations listOperations = Mockito.mock(ListOperations.class);
ZSetOperations zSetOperations = Mockito.mock(ZSetOperations.class);
when(redisTemplate.opsForSet()).thenReturn(setOperations);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(redisTemplate.opsForHash()).thenReturn(hashOperations);
when(redisTemplate.opsForList()).thenReturn(listOperations);
when(redisTemplate.opsForZSet()).thenReturn(zSetOperations);
BoundListOperations boundListOperations = Mockito.mock(BoundListOperations.class);
when(redisTemplate.boundListOps(key)).thenReturn(boundListOperations);
BoundValueOperations boundValueOperations = Mockito.mock(BoundValueOperations.class);
when(redisTemplate.boundValueOps(key)).thenReturn(boundValueOperations);
BoundHashOperations boundHashOperations = Mockito.mock(BoundHashOperations.class);
when(redisTemplate.boundHashOps(key)).thenReturn(boundHashOperations);
BoundSetOperations boundSetOperations = Mockito.mock(BoundSetOperations.class);
when(redisTemplate.boundSetOps(key)).thenReturn(boundSetOperations);
RedisOperations redisOperations = Mockito.mock(RedisOperations.class);
RedisConnection redisConnection = Mockito.mock(RedisConnection.class);
RedisConnectionFactory redisConnectionFactory = Mockito.mock(RedisConnectionFactory.class);
when(redisTemplate.getConnectionFactory()).thenReturn(redisConnectionFactory);
when(valueOperations.getOperations()).thenReturn(redisOperations);
when(redisTemplate.getConnectionFactory().getConnection()).thenReturn(redisConnection);
}
}
经过测试后成功对RedisTemplate进行Mock文章来源地址https://www.toymoban.com/news/detail-519733.html
@BeforeEach()
public void redisTemplateMock(){
this.redisTemplate = RedisTemplateMockUtil.mockRedisTemplate(redisTemplate,"BOUND_KEY");
}
到了这里,关于Mockito无法Mock RedisTemplate解决方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!