SpringBoot单元测试中使⽤mockito框架mock掉整个
RedisTemplate的⽰例
概述
当我们使⽤单元测试来验证应⽤程序代码时,如果代码中需要访问Redis,那么为了保证单元测试不依赖Redis,需要将整
个Redis mock掉。在Spring Boot中结合mockito很容易做到这⼀点,如下代码:
spring framework面试题kito.Mockito;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.tion.RedisConnection;
import org.tion.RedisConnectionFactory;
import org.*;
import st.context.ActiveProfiles;
import kito.Mockito.when;
/**
* mock掉整个RedisTemplate
*/
@ActiveProfiles("uttest")
@Configuration
public class RedisTemplateMocker {
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = k(RedisTemplate.class);
ValueOperations valueOperations = k(ValueOperations.class);
SetOperations setOperations = k(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 = k(RedisOperations.class);
RedisConnection redisConnection = k(RedisConnection.class);
RedisConnectionFactory redisConnectionFactory = k(RedisConnectionFactory.class);
ConnectionFactory()).thenReturn(redisConnectionFactory);
Operations()).thenReturn(redisOperations);
ConnectionFactory().getConnection()).thenReturn(redisConnection);
return redisTemplate;
}
}
上⾯的代码已经mock掉⼤部分的Redis操作了,⽹友想mock掉其他操作,⾃⾏加上即可。
总结
以上就是这篇⽂章的全部内容了,希望本⽂的内容对⼤家的学习或者⼯作具有⼀定的参考学习价值,谢谢⼤家对的⽀持。如果你想了解更多相关内容请查看下⾯相关链接
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论