Spring Boot Rest控制器单元测试过程解析

所属分类: 软件编程 / java 阅读数: 48
收藏 0 赞 0 分享

Spring Boot提供了一种为Rest Controller文件编写单元测试的简便方法。在SpringJUnit4ClassRunner和MockMvc的帮助下,可以创建一个Web应用程序上下文来为Rest Controller文件编写单元测试。
单元测试应该写在src/test/java目录下,用于编写测试的类路径资源应该放在src/test/resources目录下。
对于编写单元测试,需要在构建配置文件中添加Spring Boot Starter Test依赖项,如下所示。

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
</dependency>

XML

Gradle用户可以在build.gradle 文件中添加以下依赖项。

testCompile(‘org.springframework.boot:spring-boot-starter-test‘)

在编写测试用例之前,应该先构建RESTful Web服务。 有关构建RESTful Web服务的更多信息,请参阅本教程中给出的相同章节。

编写REST控制器的单元测试

在本节中,看看如何为REST控制器编写单元测试。

首先,需要创建用于通过使用MockMvc创建Web应用程序上下文的Abstract类文件,并定义mapToJson()和mapFromJson()方法以将Java对象转换为JSON字符串并将JSON字符串转换为Java对象。

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)
@WebAppConfiguration
public 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);
 }
}

接下来,编写一个扩展AbstractTest类的类文件,并为每个方法(如GET,POST,PUT和DELETE)编写单元测试。

下面给出了GET API测试用例的代码。 此API用于查看产品列表。

@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);
}

POST API测试用例的代码如下。 此API用于创建产品。

@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");
}

下面给出了PUT API测试用例的代码。 此API用于更新现有产品。

@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");
}

Delete API测试用例的代码如下。 此API将删除现有产品。

@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");
}

完整的控制器测试类文件代码如下 -

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");
 }
}

创建一个可执行的JAR文件,并使用下面给出的Maven或Gradle命令运行Spring Boot应用程序 -

对于Maven,可以使用下面给出的命令

mvn clean install

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

SpringBoot中使用Ehcache的详细教程

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认的 CacheProvider。这篇文章主要介绍了SpringBoot中使用Ehcache的相关知识,需要的朋友可以参考下
收藏 0 赞 0 分享

在idea 中添加和删除模块Module操作

这篇文章主要介绍了在idea 中添加和删除模块Module操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java spring整合junit操作(有详细的分析过程)

这篇文章主要介绍了java spring整合junit操作(有详细的分析过程),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解JAVA 弱引用

这篇文章主要介绍了 JAVA 弱引用的相关资料,帮助大家更好的理解和学习java引用对象,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

深入了解JAVA 虚引用

这篇文章主要介绍了JAVA 虚引用的相关资料,帮助大家更好的理解和学习JAVA,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

详解JAVA 强引用

这篇文章主要介绍了JAVA 强引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

java中的按位与(&)用法说明

这篇文章主要介绍了java中的按位与(&)用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

深入了解JAVA 软引用

这篇文章主要介绍了JAVA 软引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

利用MyBatis实现条件查询的方法汇总

这篇文章主要给大家介绍了关于利用MyBatis实现条件查询的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用MyBatis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
收藏 0 赞 0 分享

Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.PathTranslator was bound

这篇文章主要介绍了Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.Pa
收藏 0 赞 0 分享
查看更多