自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

有啥不同?來看看Spring Boot基于JUnit 5實(shí)現(xiàn)單元測(cè)試

開發(fā) 后端 測(cè)試
本文介紹 Spring Boot 2 基于 JUnit 5 的單元測(cè)試實(shí)現(xiàn)方案。一起來看看吧。

[[334436]]

 目錄

  •  簡(jiǎn)介
  •  JUnit 4 和 JUnit 5 的差異
    •   忽略測(cè)試用例執(zhí)行
    •   RunWith 配置
    •   @Before、@BeforeClass、@After、@AfterClass 被替換
  •  開發(fā)環(huán)境
  •  示例

簡(jiǎn)介

Spring Boot 2.2.0 版本開始引入 JUnit 5 作為單元測(cè)試默認(rèn)庫,在 Spring Boot 2.2.0 版本之前,spring-boot-starter-test 包含了 JUnit 4 的依賴,Spring Boot 2.2.0 版本之后替換成了 Junit Jupiter。

JUnit 4 和 JUnit 5 的差異

1. 忽略測(cè)試用例執(zhí)行

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

開發(fā)環(huán)境

  •  JDK 8

示例

1.創(chuàng)建 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.工程創(chuàng)建好之后自動(dòng)生成了一個(gè)測(cè)試類。 

  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.     }  

這個(gè)測(cè)試類的作用是檢查應(yīng)用程序上下文是否可正常啟動(dòng)。@SpringBootTest 注解告訴 Spring Boot 查找?guī)?@SpringBootApplication 注解的主配置類,并使用該類啟動(dòng) Spring 應(yīng)用程序上下文。Java知音公眾號(hào)內(nèi)回復(fù)“后端面試”, 送你一份Java面試題寶典

4.補(bǔ)充待測(cè)試應(yīng)用邏輯代碼

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 層實(shí)現(xiàn) 

  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.編寫發(fā)送 HTTP 請(qǐng)求的單元測(cè)試。 

  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 使用本地的一個(gè)隨機(jī)端口啟動(dòng)服務(wù);
  •  @LocalServerPort 相當(dāng)于 @Value("${local.server.port}");
  •  在配置了 webEnvironment 后,Spring Boot 會(huì)自動(dòng)提供一個(gè) TestRestTemplate 實(shí)例,可用于發(fā)送 HTTP 請(qǐng)求。
  •  除了使用 TestRestTemplate 實(shí)例發(fā)送 HTTP 請(qǐng)求外,還可以借助 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.     }  

以上測(cè)試方法屬于整體測(cè)試,即將應(yīng)用上下文全都啟動(dòng)起來,還有一種分層測(cè)試方法,譬如僅測(cè)試 Controller 層。

6.分層測(cè)試。 

  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 僅實(shí)例化 Controller 層,而不去實(shí)例化整體上下文,還可以進(jìn)一步指定僅實(shí)例化 Controller 層的某個(gè)實(shí)例:@WebMvcTest(HelloController.class);

因?yàn)橹粚?shí)例化了 Controller 層,所以依賴的 Service 層實(shí)例需要通過 @MockBean 創(chuàng)建,并通過 Mockito 的方法指定 Mock 出來的 Service 層實(shí)例在特定情況下方法調(diào)用時(shí)的返回結(jié)果。 

 

責(zé)任編輯:龐桂玉 來源: Java知音
相關(guān)推薦

2021-01-07 14:06:30

Spring BootJUnit5Java

2021-08-26 11:00:54

Spring BootJUnit5Java

2021-09-01 12:03:49

Spring單元測(cè)試

2017-01-14 23:26:17

單元測(cè)試JUnit測(cè)試

2017-01-16 12:12:29

單元測(cè)試JUnit

2011-08-11 13:02:43

Struts2Junit

2023-09-27 23:43:51

單元測(cè)試Spring

2011-11-18 15:18:41

Junit單元測(cè)試Java

2013-06-04 09:49:04

Spring單元測(cè)試軟件測(cè)試

2023-12-28 17:36:10

JUnit5單元測(cè)試框架

2017-01-14 23:42:49

單元測(cè)試框架軟件測(cè)試

2012-02-07 09:08:50

Feed4JUnitJava

2012-07-22 20:34:27

springMVCJUnit

2010-10-13 09:29:53

JUnit單元測(cè)試Android

2009-06-08 19:59:09

EclipseJUnit單元測(cè)試

2009-06-08 19:57:29

EclipseJUnit4單元測(cè)試

2021-12-07 07:01:21

Python病毒 文件

2009-06-08 20:04:06

EclipseJUnit4單元測(cè)試

2014-02-25 10:25:52

單元測(cè)試測(cè)試

2020-08-18 08:10:02

單元測(cè)試Java
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)