有啥不同?来看看Spring Boot基于JUnit 5实现单元测试

开发 后端 测试
本文介绍 Spring Boot 2 基于 JUnit 5 的单元测试实现方案。一起来看看吧。

[[334436]]

 目录

  •  简介
  •  JUnit 4 和 JUnit 5 的差异
    •   忽略测试用例执行
    •   RunWith 配置
    •   @Before、@BeforeClass、@After、@AfterClass 被替换
  •  开发环境
  •  示例

简介

Spring Boot 2.2.0 版本开始引入 JUnit 5 作为单元测试默认库,在 Spring Boot 2.2.0 版本之前,spring-boot-starter-test 包含了 JUnit 4 的依赖,Spring Boot 2.2.0 版本之后替换成了 Junit Jupiter。

JUnit 4 和 JUnit 5 的差异

1. 忽略测试用例执行

JUnit 4: 

  1. @Test  
  2. @Ignore  
  3. public void testMethod() {  
  4.    // ...  

JUnit 5: 

  1. @Test  
  2. @Disabled("explanation")  
  3. public void testMethod() {  
  4.    // ...  

2. RunWith 配置

JUnit 4: 

  1. @RunWith(SpringRunner.class)  
  2. @SpringBootTest  
  3. public class ApplicationTests {  
  4.     @Test  
  5.     public void contextLoads() {  
  6.     }  

JUnit 5: 

  1. @ExtendWith(SpringExtension.class)  
  2. @SpringBootTest 
  3. public class ApplicationTests {  
  4.     @Test  
  5.     public void contextLoads() {  
  6.     }  

3. @Before、@BeforeClass、@After、@AfterClass 被替换

  •  @BeforeEach 替换 @Before
  •  @BeforeAll 替换 @BeforeClass
  •  @AfterEach 替换 @After
  •  @AfterAll 替换 @AfterClass

开发环境

  •  JDK 8

示例

1.创建 Spring Boot 工程。

2.添加 spring-boot-starter-web 依赖,最终 pom.xml 如下。 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.     <modelVersion>4.0.0</modelVersion>  
  5.     <parent>  
  6.         <groupId>org.springframework.boot</groupId>  
  7.         <artifactId>spring-boot-starter-parent</artifactId>  
  8.         <version>2.2.6.RELEASE</version>  
  9.         <relativePath/>  
  10.     </parent>  
  11.     <groupId>tutorial.spring.boot</groupId>  
  12.     <artifactId>spring-boot-junit5</artifactId>  
  13.     <version>0.0.1-SNAPSHOT</version>  
  14.     <name>spring-boot-junit5</name>  
  15.     <description>Demo project for Spring Boot Unit Test with JUnit 5</description>  
  16.     <properties>  
  17.         <java.version>1.8</java.version>  
  18.     </properties>  
  19.     <dependencies>  
  20.         <dependency>  
  21.             <groupId>org.springframework.boot</groupId>  
  22.             <artifactId>spring-boot-starter-web</artifactId>  
  23.         </dependency>  
  24.         <dependency>  
  25.             <groupId>org.springframework.boot</groupId>  
  26.             <artifactId>spring-boot-starter-test</artifactId>  
  27.             <scope>test</scope>  
  28.             <exclusions> 
  29.                  <exclusion>  
  30.                     <groupId>org.junit.vintage</groupId>  
  31.                     <artifactId>junit-vintage-engine</artifactId>  
  32.                 </exclusion>  
  33.             </exclusions>  
  34.         </dependency>  
  35.     </dependencies>  
  36.     <build>  
  37.         <plugins>  
  38.             <plugin>  
  39.                 <groupId>org.springframework.boot</groupId>  
  40.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  41.             </plugin>  
  42.         </plugins>  
  43.     </build> 
  44. </project> 

3.工程创建好之后自动生成了一个测试类。 

  1. package tutorial.spring.boot.junit5;  
  2. import org.junit.jupiter.api.Test;  
  3. import org.springframework.boot.test.context.SpringBootTest;  
  4. @SpringBootTest  
  5. class SpringBootJunit5ApplicationTests {  
  6.     @Test  
  7.     void contextLoads() {  
  8.     }  

这个测试类的作用是检查应用程序上下文是否可正常启动。@SpringBootTest 注解告诉 Spring Boot 查找带 @SpringBootApplication 注解的主配置类,并使用该类启动 Spring 应用程序上下文。Java知音公众号内回复“后端面试”, 送你一份Java面试题宝典

4.补充待测试应用逻辑代码

4.1. 定义 Service 层接口 

  1. package tutorial.spring.boot.junit5.service;  
  2. public interface HelloService { 
  3.     String hello(String name);  

4.2. 定义 Controller 层 

  1. package tutorial.spring.boot.junit5.controller;  
  2. import org.springframework.web.bind.annotation.GetMapping;  
  3. import org.springframework.web.bind.annotation.PathVariable;  
  4. import org.springframework.web.bind.annotation.RestController;  
  5. import tutorial.spring.boot.junit5.service.HelloService;  
  6. @RestController  
  7. public class HelloController {  
  8.     private final HelloService helloService;  
  9.     public HelloController(HelloService helloService) { 
  10.         this.helloService = helloService;  
  11.     }  
  12.     @GetMapping("/hello/{name}")  
  13.     public String hello(@PathVariable("name") String name) {  
  14.         return helloService.hello(name);  
  15.     }  

4.3. 定义 Service 层实现 

  1. package tutorial.spring.boot.junit5.service.impl;  
  2. import org.springframework.stereotype.Service;  
  3. import tutorial.spring.boot.junit5.service.HelloService;  
  4. @Service 
  5. public class HelloServiceImpl implements HelloService {  
  6.     @Override  
  7.     public String hello(String name) {  
  8.         return "Hello, " + name;  
  9.     }  

5.编写发送 HTTP 请求的单元测试。 

  1. package tutorial.spring.boot.junit5;  
  2. import org.assertj.core.api.Assertions;  
  3. import org.junit.jupiter.api.Test;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.boot.test.context.SpringBootTest;  
  6. import org.springframework.boot.test.web.client.TestRestTemplate;  
  7. import org.springframework.boot.web.server.LocalServerPort;  
  8. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)  
  9. public class HttpRequestTest {  
  10.     @LocalServerPort  
  11.     private int port;  
  12.     @Autowired  
  13.     private TestRestTemplate restTemplate; 
  14.     @Test  
  15.     public void testHello() {  
  16.         String requestResult = this.restTemplate.getForObject("http://127.0.0.1:" + port + "/hello/spring",  
  17.                 String.class);  
  18.         Assertions.assertThat(requestResult).contains("Hello, spring");  
  19.     }  

说明:

  •  webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT 使用本地的一个随机端口启动服务;
  •  @LocalServerPort 相当于 @Value("${local.server.port}");
  •  在配置了 webEnvironment 后,Spring Boot 会自动提供一个 TestRestTemplate 实例,可用于发送 HTTP 请求。
  •  除了使用 TestRestTemplate 实例发送 HTTP 请求外,还可以借助 org.springframework.test.web.servlet.MockMvc 完成类似功能,代码如下: 
  1. package tutorial.spring.boot.junit5.controller;  
  2. import org.assertj.core.api.Assertions;  
  3. import org.junit.jupiter.api.Test;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;  
  6. import org.springframework.boot.test.context.SpringBootTest;  
  7. import org.springframework.test.web.servlet.MockMvc;  
  8. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;  
  9. import org.springframework.test.web.servlet.result.MockMvcResultHandlers;  
  10. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;  
  11. @SpringBootTest  
  12. @AutoConfigureMockMvc  
  13. public class HelloControllerTest {  
  14.     @Autowired  
  15.     private HelloController helloController;  
  16.     @Autowired  
  17.     private MockMvc mockMvc;  
  18.     @Test  
  19.     public void testNotNull() {  
  20.         Assertions.assertThat(helloController).isNotNull();  
  21.     }  
  22.     @Test  
  23.     public void testHello() throws Exception {  
  24.         this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/spring"))  
  25.                 .andDo(MockMvcResultHandlers.print())  
  26.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  27.                 .andExpect(MockMvcResultMatchers.content().string("Hello, spring")); 
  28.     }  

以上测试方法属于整体测试,即将应用上下文全都启动起来,还有一种分层测试方法,譬如仅测试 Controller 层。

6.分层测试。 

  1. package tutorial.spring.boot.junit5.controller;  
  2. import org.assertj.core.api.Assertions;  
  3. import org.junit.jupiter.api.Test;  
  4. import org.mockito.Mockito;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;  
  7. import org.springframework.boot.test.mock.mockito.MockBean;  
  8. import org.springframework.test.web.servlet.MockMvc;  
  9. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;  
  10. import org.springframework.test.web.servlet.result.MockMvcResultHandlers;  
  11. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;  
  12. import tutorial.spring.boot.junit5.service.HelloService;  
  13. @WebMvcTest  
  14. public class HelloControllerTest {  
  15.     @Autowired  
  16.     private HelloController helloController;  
  17.     @Autowired  
  18.     private MockMvc mockMvc; 
  19.     @MockBean  
  20.     private HelloService helloService;  
  21.     @Test  
  22.     public void testNotNull() {  
  23.         Assertions.assertThat(helloController).isNotNull();  
  24.     }  
  25.     @Test  
  26.     public void testHello() throws Exception {  
  27.         Mockito.when(helloService.hello(Mockito.anyString())).thenReturn("Mock hello");  
  28.         this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/spring"))  
  29.                 .andDo(MockMvcResultHandlers.print())  
  30.                 .andExpect(MockMvcResultMatchers.status().isOk())  
  31.                 .andExpect(MockMvcResultMatchers.content().string("Mock hello"));  
  32.     }  

说明:

@WebMvcTest 注释告诉 Spring Boot 仅实例化 Controller 层,而不去实例化整体上下文,还可以进一步指定仅实例化 Controller 层的某个实例:@WebMvcTest(HelloController.class);

因为只实例化了 Controller 层,所以依赖的 Service 层实例需要通过 @MockBean 创建,并通过 Mockito 的方法指定 Mock 出来的 Service 层实例在特定情况下方法调用时的返回结果。 

 

责任编辑:庞桂玉 来源: Java知音
相关推荐

2021-01-07 14:06:30

Spring BootJUnit5Java

2021-08-26 11:00:54

Spring BootJUnit5Java

2021-09-01 12:03:49

Spring单元测试

2017-01-14 23:26:17

单元测试JUnit测试

2017-01-16 12:12:29

单元测试JUnit

2011-08-11 13:02:43

Struts2Junit

2023-09-27 23:43:51

单元测试Spring

2011-11-18 15:18:41

Junit单元测试Java

2013-06-04 09:49:04

Spring单元测试软件测试

2023-12-28 17:36:10

JUnit5单元测试框架

2012-02-07 09:08:50

Feed4JUnitJava

2017-01-14 23:42:49

单元测试框架软件测试

2012-07-22 20:34:27

springMVCJUnit

2010-10-13 09:29:53

JUnit单元测试Android

2009-06-08 19:57:29

EclipseJUnit4单元测试

2009-06-08 19:59:09

EclipseJUnit单元测试

2009-06-08 20:04:06

EclipseJUnit4单元测试

2014-02-25 10:25:52

单元测试测试

2021-12-07 07:01:21

Python病毒 文件

2011-11-30 22:03:49

ibmdwJava
点赞
收藏

51CTO技术栈公众号