日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

SpringBoot应用的集成测试

發布時間:2025/5/22 57 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot应用的集成测试 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、概念和定義

進行軟件開發的時候,我們會寫很多代碼,不過,再過六個月(甚至一年以上)你知道自己的代碼怎么運作么?
通過測試(單元測試、集成測試、接口測試)可以保證系統的可維護性,當我們修改了某些代碼時,通過回歸測試可以檢查是否引入了新的bug。
總的來說,測試讓系統不再是一個黑盒子,讓開發人員確認系統可用。

二、新建測試項目

1、test類

PersonApplicationTest.java,內容是:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PersonApplication.class)
public class PersonApplicationTests {
@Test
public void contextLoads() {
}
}

2、pom依賴

在pom文件中增加spring-boot-starter-test依賴,添加jsonPath依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
</dependency>

3、在PersonApplicationTest中添加測試用例

package com.tianhe.example.Person;

import com.test.Person.domain.Book;
import com.test.Person.repository.BookRepository;
import org.junit.Before;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PersonApplication.class)
@WebIntegrationTest("server.port:0")
public class PersonApplicationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private BookRepository bookRepository;
@Value("${local.server.port}")
private int port;

private MockMvc mockMvc;
private RestTemplate restTemplate = new TestRestTemplate();

@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}

@Test
public void contextLoads() {
assertEquals(1, bookRepository.count());
}

@Test
public void webappBookIsbnApi() {
Book book = restTemplate.getForObject("http://localhost:" + port +"/books/9876-5432-1111", Book.class);
assertNotNull(book);
assertEquals("中文測試", book.getPublisher().getName());
}

@Test
public void webappPublisherApi() throws Exception {
mockMvc.perform(get("/publishers/1")
.accept(MediaType.APPLICATION_JSON_UTF8))

.andExpect(status().isOk())
.andExpect(content().string(containsString("中文測試")))
.andExpect(jsonPath("$.name").value("中文測試"));
}
}

二、spring boot項目的代碼覆蓋率

1、使用cobertura

參考項目的github地址:spring boot template

# To create test coverage reports (in target/site/cobertura)
mvn clean cobertura:cobertura test

cobertura統計代碼覆蓋率

單擊某個類進去,可以看到詳細信息
分析

首先分析在PersonApplicationTests類中用到的注解:

@RunWith(SpringJUnit4ClassRunner.class),這是JUnit的注解,通過這個注解讓SpringJUnit4ClassRunner這個類提供Spring測試上下文。
@SpringApplicationConfiguration(classes = PersonApplication.class),這是Spring Boot注解,為了進行集成測試,需要通過這個注解加載和配置Spring應用上下文。這是一個元注解(meta-annoation),它包含了@ContextConfiguration( loader = SpringApplicationContextLoader.class)這個注解,測試框架通過這個注解使用Spring Boot框架的SpringApplicationContextLoader加載器創建應用上下文。
@WebIntegrationTest("server.port:0"),這個注解表示當前的測試是集成測試(integration test),因此需要初始化完整的上下文并啟動應用程序。這個注解一般和@SpringApplicationConfiguration一起出現。server.port:0指的是讓Spring Boot在隨機端口上啟動Tomcat服務,隨后在測試中程序通過@Value("${local.server.port}")獲得這個端口號,并賦值給port變量。當在Jenkins或其他持續集成服務器上運行測試程序時,這種隨機獲取端口的能力可以提供測試程序的并行性。
了解完測試類的注解,再看看測試類的內部。由于這是Spring Boot的測試,因此我們可通過@Autowired注解織入任何由Spring管理的對象,或者是通過@Value設置指定的環境變量的值。在現在這個測試類中,我們定義了WebApplicationContext和BookRepository對象。

每個測試用例用@Test注解修飾。在第一個測試用例——contextLoads()方法中,我僅僅需要確認BookRepository連接已經建立,并且數據庫中已經包含了對應的測試數據。

第二個測試用例用來測試我們提供的RESTful URL——通過ISBN查詢一本書,即“/books/{isbn}”。在這個測試用例中我們使用TestRestTemplate對象發起RESTful請求。

第三個測試用例中展示了如何通過MockMvc對象實現跟第二個測試類似的功能。Spring測試框架提供MockMvc對象,可以在不需要客戶端-服務端請求的情況下進行MVC測試,完全在服務端這邊就可以執行Controller的請求,跟啟動了測試服務器一樣。

測試開始之前需要建立測試環境,setup方法被@Before修飾。通過MockMvcBuilders工具,使用WebApplicationContext對象作為參數,創建一個MockMvc對象。

MockMvc對象提供一組工具函數用來執行assert判斷,都是針對web請求的判斷。這組工具的使用方式是函數的鏈式調用,允許程序員將多個測試用例鏈接在一起,并進行多個判斷。在這個例子中我們用到下面的一些工具函數:

perform(get(...))建立web請求。在我們的第三個用例中,通過MockMvcRequestBuilder執行GET請求。
andExpect(...)可以在perform(...)函數調用后多次調用,表示對多個條件的判斷,這個函數的參數類型是ResultMatcher接口,在MockMvcResultMatchers這這個類中提供了很多返回ResultMatcher接口的工具函數。這個函數使得可以檢測同一個web請求的多個方面,包括HTTP響應狀態碼(response status),響應的內容類型(content type),會話中存放的值,檢驗重定向、model或者header的內容等等。這里需要通過第三方庫json-path檢測JSON格式的響應數據:檢查json數據包含正確的元素類型和對應的值,例如jsonPath("$.name").value("中文測試")用于檢查在根目錄下有一個名為name的節點,并且該節點對應的值是“中文測試”。
一個字符亂碼問題

2、問題描述:通過spring-boot-starter-data-rest建立的repository,取出的漢字是亂碼。

分析:使用postman和httpie驗證都沒問題,說明是Mockmvc的測試用例寫得不對,應該主動設置客戶端如何解析HTTP響應,用get.accept方法設置客戶端可識別的內容類型,修改后的測試用例如下:

@Test
public void webappPublisherApi() throws Exception {
mockMvc.perform(get("/publishers/1")
.accept(MediaType.APPLICATION_JSON_UTF8))

.andExpect(status().isOk())
.andExpect(content().string(containsString("中文測試")))
.andExpect(jsonPath("$.name").value("中文測試"));
}

轉載于:https://www.cnblogs.com/lexiaofei/p/7647916.html

總結

以上是生活随笔為你收集整理的SpringBoot应用的集成测试的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。