Spring Boot Rest控制器單元測(cè)試過程解析
Spring Boot提供了一種為Rest Controller文件編寫單元測(cè)試的簡(jiǎn)便方法。在SpringJUnit4ClassRunner和MockMvc的幫助下,可以創(chuàng)建一個(gè)Web應(yīng)用程序上下文來為Rest Controller文件編寫單元測(cè)試。單元測(cè)試應(yīng)該寫在src/test/java目錄下,用于編寫測(cè)試的類路徑資源應(yīng)該放在src/test/resources目錄下。對(duì)于編寫單元測(cè)試,需要在構(gòu)建配置文件中添加Spring Boot Starter Test依賴項(xiàng),如下所示。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency>
XML
Gradle用戶可以在build.gradle 文件中添加以下依賴項(xiàng)。
testCompile(‘org.springframework.boot:spring-boot-starter-test‘)
在編寫測(cè)試用例之前,應(yīng)該先構(gòu)建RESTful Web服務(wù)。 有關(guān)構(gòu)建RESTful Web服務(wù)的更多信息,請(qǐng)參閱本教程中給出的相同章節(jié)。
編寫REST控制器的單元測(cè)試
在本節(jié)中,看看如何為REST控制器編寫單元測(cè)試。
首先,需要?jiǎng)?chuàng)建用于通過使用MockMvc創(chuàng)建Web應(yīng)用程序上下文的Abstract類文件,并定義mapToJson()和mapFromJson()方法以將Java對(duì)象轉(zhuǎn)換為JSON字符串并將JSON字符串轉(zhuǎn)換為Java對(duì)象。
package com.yiibai.demo;import java.io.IOException;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.ObjectMapper;@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = DemoApplication.class)@WebAppConfigurationpublic abstract class AbstractTest { protected MockMvc mvc; @Autowired WebApplicationContext webApplicationContext; protected void setUp() { mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } protected String mapToJson(Object obj) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(obj); } protected <T> T mapFromJson(String json, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, clazz); }}
接下來,編寫一個(gè)擴(kuò)展AbstractTest類的類文件,并為每個(gè)方法(如GET,POST,PUT和DELETE)編寫單元測(cè)試。
下面給出了GET API測(cè)試用例的代碼。 此API用于查看產(chǎn)品列表。
@Testpublic void getProductsList() throws Exception { String uri = '/products'; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0);}
POST API測(cè)試用例的代碼如下。 此API用于創(chuàng)建產(chǎn)品。
@Testpublic void createProduct() throws Exception { String uri = '/products'; Product product = new Product(); product.setId('3'); product.setName('Ginger'); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, 'Product is created successfully');}
下面給出了PUT API測(cè)試用例的代碼。 此API用于更新現(xiàn)有產(chǎn)品。
@Testpublic void updateProduct() throws Exception { String uri = '/products/2'; Product product = new Product(); product.setName('Lemon'); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, 'Product is updated successsfully');}
Delete API測(cè)試用例的代碼如下。 此API將刪除現(xiàn)有產(chǎn)品。
@Testpublic void deleteProduct() throws Exception { String uri = '/products/2'; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, 'Product is deleted successsfully');}
完整的控制器測(cè)試類文件代碼如下 -
package com.yiibai.demo;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertTrue;import org.junit.Before;import org.junit.Test;import org.springframework.http.MediaType;import org.springframework.test.web.servlet.MvcResult;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import com.yiibai.demo.model.Product;public class ProductServiceControllerTest extends AbstractTest { @Override @Before public void setUp() { super.setUp(); } @Test public void getProductsList() throws Exception { String uri = '/products'; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } @Test public void createProduct() throws Exception { String uri = '/products'; Product product = new Product(); product.setId('3'); product.setName('Ginger'); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, 'Product is created successfully'); } @Test public void updateProduct() throws Exception { String uri = '/products/2'; Product product = new Product(); product.setName('Lemon'); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, 'Product is updated successsfully'); } @Test public void deleteProduct() throws Exception { String uri = '/products/2'; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, 'Product is deleted successsfully'); }}
創(chuàng)建一個(gè)可執(zhí)行的JAR文件,并使用下面給出的Maven或Gradle命令運(yùn)行Spring Boot應(yīng)用程序 -
對(duì)于Maven,可以使用下面給出的命令
mvn clean install
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 教你JS更簡(jiǎn)單的獲取表單中數(shù)據(jù)(formdata)2. python b站視頻下載的五種版本3. JAVA抽象類及接口使用方法解析4. 測(cè)試模式 - XSL教程 - 55. Python結(jié)合百度語(yǔ)音識(shí)別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn)6. 如何通過vscode運(yùn)行調(diào)試javascript代碼7. 半小時(shí)實(shí)現(xiàn)Java手?jǐn)]網(wǎng)絡(luò)爬蟲框架(附完整源碼)8. 《CSS3實(shí)戰(zhàn)》筆記--漸變?cè)O(shè)計(jì)(一)9. python如何寫個(gè)俄羅斯方塊10. JavaScript設(shè)計(jì)模式之策略模式實(shí)現(xiàn)原理詳解
![半小時(shí)實(shí)現(xiàn)Java手?jǐn)]網(wǎng)絡(luò)爬蟲框架(附完整源碼)](http://www.cgvv.com.cn/attached/image/8.jpg)