Spring Boot Rest控制器单元测试过程解析
SpringBoot提供了一种为RestController文件编写单元测试的简便方法。在SpringJUnit4ClassRunner和MockMvc的帮助下,可以创建一个Web应用程序上下文来为RestController文件编写单元测试。
单元测试应该写在src/test/java目录下,用于编写测试的类路径资源应该放在src/test/resources目录下。
对于编写单元测试,需要在构建配置文件中添加SpringBootStarterTest依赖项,如下所示。
org.springframework.boot spring-boot-starter-test test
XML
Gradle用户可以在build.gradle文件中添加以下依赖项。
testCompile(‘org.springframework.boot:spring-boot-starter-test‘)
在编写测试用例之前,应该先构建RESTfulWeb服务。有关构建RESTfulWeb服务的更多信息,请参阅本教程中给出的相同章节。
编写REST控制器的单元测试
在本节中,看看如何为REST控制器编写单元测试。
首先,需要创建用于通过使用MockMvc创建Web应用程序上下文的Abstract类文件,并定义mapToJson()和mapFromJson()方法以将Java对象转换为JSON字符串并将JSON字符串转换为Java对象。
packagecom.yiibai.demo;
importjava.io.IOException;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
importorg.springframework.test.context.web.WebAppConfiguration;
importorg.springframework.test.web.servlet.MockMvc;
importorg.springframework.test.web.servlet.setup.MockMvcBuilders;
importorg.springframework.web.context.WebApplicationContext;
importcom.fasterxml.jackson.core.JsonParseException;
importcom.fasterxml.jackson.core.JsonProcessingException;
importcom.fasterxml.jackson.databind.JsonMappingException;
importcom.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=DemoApplication.class)
@WebAppConfiguration
publicabstractclassAbstractTest{
protectedMockMvcmvc;
@Autowired
WebApplicationContextwebApplicationContext;
protectedvoidsetUp(){
mvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protectedStringmapToJson(Objectobj)throwsJsonProcessingException{
ObjectMapperobjectMapper=newObjectMapper();
returnobjectMapper.writeValueAsString(obj);
}
protectedTmapFromJson(Stringjson,Classclazz)
throwsJsonParseException,JsonMappingException,IOException{
ObjectMapperobjectMapper=newObjectMapper();
returnobjectMapper.readValue(json,clazz);
}
}
接下来,编写一个扩展AbstractTest类的类文件,并为每个方法(如GET,POST,PUT和DELETE)编写单元测试。
下面给出了GETAPI测试用例的代码。此API用于查看产品列表。
@Test
publicvoidgetProductsList()throwsException{
Stringuri="/products";
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.get(uri)
.accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(200,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
Product[]productlist=super.mapFromJson(content,Product[].class);
assertTrue(productlist.length>0);
}
POSTAPI测试用例的代码如下。此API用于创建产品。
@Test
publicvoidcreateProduct()throwsException{
Stringuri="/products";
Productproduct=newProduct();
product.setId("3");
product.setName("Ginger");
StringinputJson=super.mapToJson(product);
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.post(uri)
.contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(201,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
assertEquals(content,"Productiscreatedsuccessfully");
}
下面给出了PUTAPI测试用例的代码。此API用于更新现有产品。
@Test
publicvoidupdateProduct()throwsException{
Stringuri="/products/2";
Productproduct=newProduct();
product.setName("Lemon");
StringinputJson=super.mapToJson(product);
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.put(uri)
.contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(200,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
assertEquals(content,"Productisupdatedsuccesssfully");
}
DeleteAPI测试用例的代码如下。此API将删除现有产品。
@Test
publicvoiddeleteProduct()throwsException{
Stringuri="/products/2";
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(200,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
assertEquals(content,"Productisdeletedsuccesssfully");
}
完整的控制器测试类文件代码如下-
packagecom.yiibai.demo;
importstaticorg.junit.Assert.assertEquals;
importstaticorg.junit.Assert.assertTrue;
importorg.junit.Before;
importorg.junit.Test;
importorg.springframework.http.MediaType;
importorg.springframework.test.web.servlet.MvcResult;
importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;
importcom.yiibai.demo.model.Product;
publicclassProductServiceControllerTestextendsAbstractTest{
@Override
@Before
publicvoidsetUp(){
super.setUp();
}
@Test
publicvoidgetProductsList()throwsException{
Stringuri="/products";
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.get(uri)
.accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(200,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
Product[]productlist=super.mapFromJson(content,Product[].class);
assertTrue(productlist.length>0);
}
@Test
publicvoidcreateProduct()throwsException{
Stringuri="/products";
Productproduct=newProduct();
product.setId("3");
product.setName("Ginger");
StringinputJson=super.mapToJson(product);
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.post(uri)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(inputJson)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(201,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
assertEquals(content,"Productiscreatedsuccessfully");
}
@Test
publicvoidupdateProduct()throwsException{
Stringuri="/products/2";
Productproduct=newProduct();
product.setName("Lemon");
StringinputJson=super.mapToJson(product);
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.put(uri)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(inputJson)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(200,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
assertEquals(content,"Productisupdatedsuccesssfully");
}
@Test
publicvoiddeleteProduct()throwsException{
Stringuri="/products/2";
MvcResultmvcResult=mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();
intstatus=mvcResult.getResponse().getStatus();
assertEquals(200,status);
Stringcontent=mvcResult.getResponse().getContentAsString();
assertEquals(content,"Productisdeletedsuccesssfully");
}
}
创建一个可执行的JAR文件,并使用下面给出的Maven或Gradle命令运行SpringBoot应用程序-
对于Maven,可以使用下面给出的命令
mvncleaninstall
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。