javascript
SpringBoot应用的集成测试
一、概念和定義
進(jìn)行軟件開發(fā)的時候,我們會寫很多代碼,不過,再過六個月(甚至一年以上)你知道自己的代碼怎么運(yùn)作么?
通過測試(單元測試、集成測試、接口測試)可以保證系統(tǒng)的可維護(hù)性,當(dāng)我們修改了某些代碼時,通過回歸測試可以檢查是否引入了新的bug。
總的來說,測試讓系統(tǒng)不再是一個黑盒子,讓開發(fā)人員確認(rèn)系統(tǒng)可用。
二、新建測試項目
1、test類
PersonApplicationTest.java,內(nèi)容是:
@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統(tǒng)計代碼覆蓋率
單擊某個類進(jìn)去,可以看到詳細(xì)信息
分析
首先分析在PersonApplicationTests類中用到的注解:
@RunWith(SpringJUnit4ClassRunner.class),這是JUnit的注解,通過這個注解讓SpringJUnit4ClassRunner這個類提供Spring測試上下文。
@SpringApplicationConfiguration(classes = PersonApplication.class),這是Spring Boot注解,為了進(jìn)行集成測試,需要通過這個注解加載和配置Spring應(yīng)用上下文。這是一個元注解(meta-annoation),它包含了@ContextConfiguration( loader = SpringApplicationContextLoader.class)這個注解,測試框架通過這個注解使用Spring Boot框架的SpringApplicationContextLoader加載器創(chuàng)建應(yīng)用上下文。
@WebIntegrationTest("server.port:0"),這個注解表示當(dāng)前的測試是集成測試(integration test),因此需要初始化完整的上下文并啟動應(yīng)用程序。這個注解一般和@SpringApplicationConfiguration一起出現(xiàn)。server.port:0指的是讓Spring Boot在隨機(jī)端口上啟動Tomcat服務(wù),隨后在測試中程序通過@Value("${local.server.port}")獲得這個端口號,并賦值給port變量。當(dāng)在Jenkins或其他持續(xù)集成服務(wù)器上運(yùn)行測試程序時,這種隨機(jī)獲取端口的能力可以提供測試程序的并行性。
了解完測試類的注解,再看看測試類的內(nèi)部。由于這是Spring Boot的測試,因此我們可通過@Autowired注解織入任何由Spring管理的對象,或者是通過@Value設(shè)置指定的環(huán)境變量的值。在現(xiàn)在這個測試類中,我們定義了WebApplicationContext和BookRepository對象。
每個測試用例用@Test注解修飾。在第一個測試用例——contextLoads()方法中,我僅僅需要確認(rèn)BookRepository連接已經(jīng)建立,并且數(shù)據(jù)庫中已經(jīng)包含了對應(yīng)的測試數(shù)據(jù)。
第二個測試用例用來測試我們提供的RESTful URL——通過ISBN查詢一本書,即“/books/{isbn}”。在這個測試用例中我們使用TestRestTemplate對象發(fā)起RESTful請求。
第三個測試用例中展示了如何通過MockMvc對象實現(xiàn)跟第二個測試類似的功能。Spring測試框架提供MockMvc對象,可以在不需要客戶端-服務(wù)端請求的情況下進(jìn)行MVC測試,完全在服務(wù)端這邊就可以執(zhí)行Controller的請求,跟啟動了測試服務(wù)器一樣。
測試開始之前需要建立測試環(huán)境,setup方法被@Before修飾。通過MockMvcBuilders工具,使用WebApplicationContext對象作為參數(shù),創(chuàng)建一個MockMvc對象。
MockMvc對象提供一組工具函數(shù)用來執(zhí)行assert判斷,都是針對web請求的判斷。這組工具的使用方式是函數(shù)的鏈?zhǔn)秸{(diào)用,允許程序員將多個測試用例鏈接在一起,并進(jìn)行多個判斷。在這個例子中我們用到下面的一些工具函數(shù):
perform(get(...))建立web請求。在我們的第三個用例中,通過MockMvcRequestBuilder執(zhí)行GET請求。
andExpect(...)可以在perform(...)函數(shù)調(diào)用后多次調(diào)用,表示對多個條件的判斷,這個函數(shù)的參數(shù)類型是ResultMatcher接口,在MockMvcResultMatchers這這個類中提供了很多返回ResultMatcher接口的工具函數(shù)。這個函數(shù)使得可以檢測同一個web請求的多個方面,包括HTTP響應(yīng)狀態(tài)碼(response status),響應(yīng)的內(nèi)容類型(content type),會話中存放的值,檢驗重定向、model或者h(yuǎn)eader的內(nèi)容等等。這里需要通過第三方庫json-path檢測JSON格式的響應(yīng)數(shù)據(jù):檢查json數(shù)據(jù)包含正確的元素類型和對應(yīng)的值,例如jsonPath("$.name").value("中文測試")用于檢查在根目錄下有一個名為name的節(jié)點(diǎn),并且該節(jié)點(diǎn)對應(yīng)的值是“中文測試”。
一個字符亂碼問題
2、問題描述:通過spring-boot-starter-data-rest建立的repository,取出的漢字是亂碼。
分析:使用postman和httpie驗證都沒問題,說明是Mockmvc的測試用例寫得不對,應(yīng)該主動設(shè)置客戶端如何解析HTTP響應(yīng),用get.accept方法設(shè)置客戶端可識別的內(nèi)容類型,修改后的測試用例如下:
@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("中文測試"));
}
轉(zhuǎn)載于:https://www.cnblogs.com/lexiaofei/p/7647916.html
總結(jié)
以上是生活随笔為你收集整理的SpringBoot应用的集成测试的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在swt中获取jar包中的文件 uri
- 下一篇: gradle idea java ssm