Spring Boot單元測試中使用mockito框架mock掉整個RedisTemplate的示例
更新時間:2018年12月07日 08:31:43 作者:Sam哥哥
今天小編就為大家分享一篇關于Spring Boot單元測試中使用mockito框架mock掉整個RedisTemplate的示例,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
概述
當我們使用單元測試來驗證應用程序代碼時,如果代碼中需要訪問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掉其他操作,自行加上即可。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
springBoot?@Scheduled實現(xiàn)多個任務同時開始執(zhí)行
這篇文章主要介紹了springBoot?@Scheduled實現(xiàn)多個任務同時開始執(zhí)行,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
spring注解之@Valid和@Validated的區(qū)分總結
@Validated和@Valid在基本驗證功能上沒有太多區(qū)別,但在分組、注解地方、嵌套驗證等功能上有所不同,下面這篇文章主要給大家介紹了關于spring注解之@Valid和@Validated區(qū)分的相關資料,需要的朋友可以參考下2022-03-03
Java實戰(zhàn)之小米交易商城系統(tǒng)的實現(xiàn)
這篇文章將利用Java實現(xiàn)小米交易商城系統(tǒng),文中采用的技術有:JSP?、Spring、SpringMVC、MyBatis等,感興趣的小伙伴可以跟隨小編一起學習一下2022-04-04
Mybatis?MappedStatement類核心原理詳解
這篇文章主要介紹了Mybatis?MappedStatement類,mybatis的mapper文件最終會被解析器,解析成MappedStatement,其中insert|update|delete|select每一個標簽分別對應一個MappedStatement2022-11-11

