概述
當我們使用單元測試來驗證應用程序代碼時,如果代碼中需要訪問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")@Configurationpublic 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
掉其他操作,自行加上即可。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
|
新聞熱點
疑難解答
圖片精選