好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring Boot单元测试中使用mockito框架mock掉整个RedisTemplate的示例

概述

当我们使用单元测试来验证应用程序代码时,如果代码中需要访问 redis ,那么为了保证单元测试不依赖 redis ,需要将整个 redis mock 掉。在 spring boot 中结合 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;

   }

}

上面的代码已经 mock 掉大部分的 redis 操作了,网友想 mock 掉其他操作,自行加上即可。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/linsongbin1/article/details/82761965

查看更多关于Spring Boot单元测试中使用mockito框架mock掉整个RedisTemplate的示例的详细内容...

  阅读:18次