好得很程序员自学网

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

SpringBoot+JUnit5+MockMvc+Mockito单元测试的实现

今天聊聊如何在 SpringBoot 中集成 Junit5、MockMvc、Mocktio。Junit5 是在 Java 栈中应用最广的测试框架,Junit4 一度霸榜。

升级到 Junit5 之后,除了增加 Java8 的很多特性,做了很多功能增强,在结构上做了优化调整,拆分了很多不同的模块,可以按需引入,比如:

JUnit Platform - 在 JVM 上启动测试框架 JUnit Jupiter - 在 JUnit5 中编写测试和扩展 JUnit Vintage - 提供运行基于 JUnit3 和 JUnit4 的测试引擎

从 SpringBoot 2.2.0 之后,Junit5 已经成为了默认的 Junit 版本。有了 JUnit Vintage,从 Junit4 迁移到 Junit5 的成本极低。所以本文就直接针对 Junit5 开始了。

版本

先说版本,是为了避免因为版本差异出现各种奇怪的问题:

JDK:jdk8(小版本可以忽略) SpringBoot:2.5.2 继承spring-boot-starter-parent 依赖spring-boot-starter-web 依赖spring-boot-starter-test JUnit:5.7.2 Mockito:3.9.0 hamcrest:2.2

SpringBoot 的好处在于,只要继承spring-boot-starter-parent或引入spring-boot-pom-dependencies,然后添加spring-boot-starter-test依赖即可。定义的 POM 内容如下:

?

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

37

38

39

40

41

42

43

44

45

46

47

<? xml version = "1.0" encoding = "UTF-8" ?>

< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance"

          xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" >

     < modelVersion >4.0.0</ modelVersion >

     < parent >

         < groupId >org.springframework.boot</ groupId >

         < artifactId >spring-boot-starter-parent</ artifactId >

         < version >2.5.2</ version >

     </ parent >

     < groupId >cn.howardliu.effective.spring</ groupId >

     < artifactId >springboot-junit5-mockito</ artifactId >

     < version >0.0.1-SNAPSHOT</ version >

     < name >springboot-junit5-mockio</ name >

 

     < dependencies >

         < dependency >

             < groupId >org.springframework.boot</ groupId >

             < artifactId >spring-boot-starter-web</ artifactId >

         </ dependency >

 

         < dependency >

             < groupId >org.springframework.boot</ groupId >

             < artifactId >spring-boot-devtools</ artifactId >

             < scope >runtime</ scope >

             < optional >true</ optional >

         </ dependency >

         < dependency >

             < groupId >org.projectlombok</ groupId >

             < artifactId >lombok</ artifactId >

             < optional >true</ optional >

         </ dependency >

         < dependency >

             < groupId >org.springframework.boot</ groupId >

             < artifactId >spring-boot-starter-test</ artifactId >

             < scope >test</ scope >

         </ dependency >

     </ dependencies >

 

     < build >

         < plugins >

             < plugin >

                 < groupId >org.springframework.boot</ groupId >

                 < artifactId >spring-boot-maven-plugin</ artifactId >

             </ plugin >

         </ plugins >

     </ build >

</ project >

因为继承了spring-boot-starter-parent,所以我们依赖的spring-boot-starter-test不需要写具体的版本,可以直接集成父级的版本定义。其中,spring-boot-starter-web是用于提供 REST API 的 web 容器,spring-boot-starter-test可以提供各种测试框架的,spring-boot-maven-plugin是将 SpringBoot 应用打包为可执行 jar 的插件。

项目结构

因为是 DEMO 示例,我们实现一个 Echo 接口,能够接收请求参数,并返回加工后的字符串。按照惯例,我们使用万能的Hello, World!。

我们的项目结构如下:

?

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

├── pom.xml

└── src

     ├── main

     │   ├── java

     │   │   └── cn

     │   │       └── howardliu

     │   │           └── effective

     │   │               └── spring

     │   │                   └── springbootjunit5mockio

     │   │                       ├── SpringbootJunit5MockioApplication.java

     │   │                       ├── controller

     │   │                       │   └── EchoController.java

     │   │                       └── service

     │   │                           ├── EchoService.java

     │   │                           └── impl

     │   │                               └── EchoServiceImpl.java

     │   └── resources

     │       └── application.yaml

     └── test

         └── java

             └── cn

                 └── howardliu

                     └── effective

                         └── spring

                             └── springbootjunit5mockio

                                 └── controller

                                     ├── EchoControllerMockTest.java

                                     └── EchoControllerNoMockitoTest.java

SpringbootJunit5MockioApplication:SpringBoot 应用启动入口 EchoController:接口定义 EchoService:实现业务逻辑接口 EchoServiceImpl:接口实现 EchoControllerMockTest:使用 Mock 代理 EchoService 实现 EchoControllerNoMockitoTest:直接测试接口实现

EchoServiceImpl

我们看下EchoService的实现,这将是我们 DEMO 的核心实现:

?

1

2

3

4

5

6

7

@Service

public class EchoServiceImpl implements EchoService {

     @Override

     public String echo(String foo) {

         return "Hello, " + foo;

     }

}

EchoControllerNoMockitoTest

我们先使用 Junit5+MockMvc 实现 Controller 接口的普通调用,代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@SpringBootTest (classes = SpringbootJunit5MockioApplication. class )

@AutoConfigureMockMvc

class EchoControllerNoMockitoTest {

     @Autowired

     private MockMvc mockMvc;

 

     @Test

     void echo() throws Exception {

         final String result = mockMvc.perform(

                 MockMvcRequestBuilders.get( "/echo/" )

                         .param( "name" , "看山" )

         )

                 .andExpect(MockMvcResultMatchers.status().isOk())

                 .andDo(MockMvcResultHandlers.print())

                 .andReturn()

                 .getResponse()

                 .getContentAsString(StandardCharsets.UTF_8);

 

         Assertions.assertEquals( "Hello, 看山" , result);

     }

}

我们通过SpringBootTest注解定义这是一个 SpringBoot 应用的测试用例,然后通过AutoConfigureMockMvc启动测试容器。这样,就可以直接注入MockMvc实例测试 Controller 接口。

这里需要注意一点,网上很多教程会让写@ExtendWith({SpringExtension.class})这样一个注解,其实完全没有必要。通过源码我们可以知道,SpringBootTest注解已经添加了ExtendWith。

EchoControllerMockTest

这个测试用例中,我们通过 Mockito 组件代理EchoService的echo方法,代码如下:

?

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

@SpringBootTest (classes = SpringbootJunit5MockioApplication. class )

@ExtendWith (MockitoExtension. class )

@AutoConfigureMockMvc

class EchoControllerMockTest {

     @Autowired

     private MockMvc mockMvc;

     @MockBean

     private EchoService echoService;

 

     @BeforeEach

     void setUp() {

         Mockito.when(echoService.echo(Mockito.any()))

                 .thenReturn( "看山说:" + System.currentTimeMillis());

     }

 

     @Test

     void echo() throws Exception {

         final String result = mockMvc.perform(

                 MockMvcRequestBuilders.get( "/echo/" )

                         .param( "name" , "看山的小屋" )

         )

                 .andExpect(MockMvcResultMatchers.status().isOk())

                 .andDo(MockMvcResultHandlers.print())

                 .andReturn()

                 .getResponse()

                 .getContentAsString(StandardCharsets.UTF_8);

 

         Assertions.assertTrue(result.startsWith( "看山" ));

     }

}

在这个示例中,我们需要注意@ExtendWith(MockitoExtension.class)注解,这个注解是用于引入MockBean的,我们通过对echo方法的拦截,使其返回我们定义好的响应结果。这种方式是为了在多系统或者多功能测试时,不需要真正调用接口。

比如,我们需要获取用户手机号,通常在接口中会校验用户有没有登录,我们就可以使用 Mockito 的能力代理登录验证,使结果永远是 true。

到此这篇关于SpringBoot+JUnit5+MockMvc+Mockito单元测试的实现的文章就介绍到这了,更多相关SpringBoot JUnit5 MockMvc Mockito单元测试内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/liuxinghao/article/details/120244720

查看更多关于SpringBoot+JUnit5+MockMvc+Mockito单元测试的实现的详细内容...

  阅读:36次