概述
當(dāng)我們使用單元測試來驗證應(yīng)用程序代碼時,如果代碼中需要訪問redis
,那么為了保證單元測試不依賴redis
,需要將整個redis mock
掉。在spring boot
中結(jié)合mockito
很容易做到這一點,如下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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
掉其他操作,自行加上即可。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/linsongbin1/article/details/82761965