Spring Boot單元測試中使用mockito框架mock掉整個RedisTemplate的示例
概述
當我們使用單元測試來驗證應用程序代碼時,如果代碼中需要訪問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;
}
}
上面的代碼已經(jīng)mock掉大部分的Redis操作了,網(wǎng)友想mock掉其他操作,自行加上即可。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
java多線程開發(fā)ScheduledExecutorService簡化方式
這篇文章主要為大家介紹了java多線程開發(fā)ScheduledExecutorService的簡化方式,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-03-03
Java自帶定時任務ScheduledThreadPoolExecutor實現(xiàn)定時器和延時加載功能
今天小編就為大家分享一篇關于Java自帶定時任務ScheduledThreadPoolExecutor實現(xiàn)定時器和延時加載功能,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12
使用CI/CD工具Github Action發(fā)布jar到Maven中央倉庫的詳細介紹
今天通過對Github Action的簡單使用來介紹了CI/CD的作用,這個技術體系是項目集成交付的趨勢,也是面試中的一個亮點技能。 而且這種方式可以實現(xiàn)“一次配置,隨時隨地集成部署”,感興趣的朋友一起看看吧2021-07-07
springboot+vue制作后臺管理系統(tǒng)項目
本文詳細介紹了后臺管理使用springboot+vue制作,以分步驟、圖文的形式詳細講解,大家有需要的可以參考參考2021-08-08
SpringBoot日程管理Quartz與定時任務Task實現(xiàn)詳解
定時任務是企業(yè)級開發(fā)中必不可少的組成部分,諸如長周期業(yè)務數(shù)據(jù)的計算,例如年度報表,諸如系統(tǒng)臟數(shù)據(jù)的處理,再比如系統(tǒng)性能監(jiān)控報告,還有搶購類活動的商品上架,這些都離不開定時任務。本節(jié)將介紹兩種不同的定時任務技術2022-09-09

