概述
坚守“ 做人真诚 · 做事靠谱 · 口碑至上 · 高效敬业 ”的价值观,专业网站建设服务10余年为成都混凝土搅拌机小微创业公司专业提供成都企业网站定制营销网站建设商城网站建设手机网站建设小程序网站建设网站改版,从内容策划、视觉设计、底层架构、网页布局、功能开发迭代于一体的高端网站建设服务。
当我们使用单元测试来验证应用程序代码时,如果代码中需要访问redis
,那么为了保证单元测试不依赖Redis
,需要将整个Redis mock
掉。在Spring Boot
中结合mockito
很容易做到这一点,如下代码:
import org.mockito.Mockito; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.*; import org.springframework.test.context.ActiveProfiles; import static org.mockito.Mockito.when; /** * mock掉整个RedisTemplate */ @ActiveProfiles("uttest") @Configuration public class RedisTemplateMocker { @Bean public RedisTemplate redisTemplate() { RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); ValueOperations valueOperations = Mockito.mock(ValueOperations.class); SetOperations setOperations = Mockito.mock(SetOperations.class); HashOperations hashOperations = redisTemplate.opsForHash(); ListOperations listOperations = redisTemplate.opsForList(); ZSetOperations zSetOperations = redisTemplate.opsForZSet(); 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); 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); return redisTemplate; } }
上面的代码已经mock
掉大部分的Redis
操作了,网友想mock
掉其他操作,自行加上即可。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对创新互联的支持。如果你想了解更多相关内容请查看下面相关链接