Spring Boot Rest控制器单元测试

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

Java

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

下面给出了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);
}

Java

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

Java

下面给出了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");
}

Java

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

Java

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

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

Java

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

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

mvn clean install

Shell

现在,在控制台窗口中看到测试结果。

原文地址:https://www.cnblogs.com/borter/p/12423886.html

时间: 2024-08-26 07:33:50

Spring Boot Rest控制器单元测试的相关文章

【maven】【spring boot】【单元测试】 使用controller 执行单元测试类

存在这样一个场景: 当项目启动时间过长,又没办法缩短的时候,写单元测试就是一个十分耗时的工作, 这工作不在于使用编写代码,而在于每次run junit test 都需要完整启动一次项目,白白浪费宝贵的生命. 当由于某个字段没有赋值,或者某个简单判断写错,导致需要再等个3-5分钟启动 junit test,是否会想要执行一次san check? 于是乎: 假若能使用controller来调用test类方法的话,那么在本地调试单元测试时,对于一些简单的代码修改,通过热部署,只需要重新进行一次url访

Spring Boot&mdash;11控制器Controller

package com.sample.smartmap.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.spring

笔记:Spring Boot 项目构建与解析

构建 Maven 项目 通过官方的 Spring Initializr 工具来产生基础项目,访问 http://start.spring.io/ ,如下图所示,该页面提供了以Maven构建Spring Boot 项目的功能. 选择构建工具 Maven Project,Spring Boot 版本选择 1.5.4,填写 Group 和 Artifact 信息,在Search for dependencies 中可以搜索需要的其他依赖包,这里我们需要实现 RESTful API,所以可以添加 Web

最全spring boot视频系列,你值得拥有

================================== 从零开始学Spring Boot视频 ================================== àSpringBoot视频 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share [截止到201

Spring Boot系列(3)——模板引擎thymeleaf

〇.thymeleaf是什么 1.在以往开发spring web项目时,若我们想在前端页面上显示一些服务端的数据(即动态显示),得借助JSP的内置对象和JSTL实现,或者通过JavaScript请求实现:其缺点在于,与后端联系太紧密,不利于前后端分离. 2.而使用模板引擎,可以大大克服这一缺点,模板引擎可以使得前端很自然地开发(即更接近原生html). 3.模板引擎优点有:业务逻辑代码与界面代码分离.动态数据与静态数据分离.代码重用.... 4.常用模板引擎:Thymeleaf.FreeMark

Spring Boot 单元测试示例

Spring 框架提供了一个专门的测试模块(spring-test),用于应用程序的单元测试. 在 Spring Boot 中,你可以通过spring-boot-starter-test启动器快速开启和使用它. 在pom.xml文件中引入maven依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artif

spring boot?Swagger2文档构建及单元测试

首先,回顾并详细说明一下在快速入门中使用的@Controller.@RestController.@RequestMapping注解.如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下快速入门的内容. @Controller:修饰class,用来创建处理http请求的对象 @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Contro

Spring Boot的单元测试(Unit Test)

最近做了一些Spring Boot单元测试方面的东西,总结一下. 单元测试尽量要和Spring Boot框架减少耦合度,当你在测试某一项功能点是需要mock太多的对象时你就应该意识到这个功能点的耦合度太高了 使用Constructor Injection,不要使用Field Injection.这样才能更容易写单元测试代码.在Spring Framework 4.3以后,如果你只有一个Constructor, 就不再需要写@Autowired,Spring会默认他是autowire目标: pub

Spring Boot的单元测试(Unit Test)(一)

最近做了一些Spring Boot单元测试方面的东西,总结一下. 单元测试尽量要和Spring Boot框架减少耦合度,当你在测试某一项功能点是需要mock太多的对象时你就应该意识到这个功能点的耦合度太高了 使用Constructor Injection,不要使用Field Injection.这样才能更容易写单元测试代码.在Spring Framework 4.3以后,如果你只有一个Constructor, 就不再需要写@Autowired,Spring会默认他是autowire目标: pub