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

