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

接下来,编写一个扩展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

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

(0)

相关推荐

  • SpringBoot框架RESTful接口设置跨域允许

    跨域 跨域请求是指浏览器脚本文件在发送请求时,脚本所在的服务器和请求的服务器地址不一样.跨域是有浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制, 同源策略:是指协议.域名.端口都要相同,其中有一个不同都会产生跨域 SpringBoot框架RESTful接口解决跨域 此处是有配置文件的方式来解决的 package com.prereadweb.config.cors; import org.springframework.context.annotation.Bean; im

  • Springboot RestTemplate 简单使用解析

    前言 spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可. 相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式.该类主要用到的函数有:exchange.getForEntity.postForEntity等.我主要用的是后面两个函数,来执行发送get跟post请求. 首先是RestTemplat

  • 详解SpringBoot中RestTemplate的几种实现

    RestTemplate的多种实现 使用JDK默认的http library 使用Apache提供的httpclient 使用Okhttp3 @Configuration public class RestConfig { @Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); return restTemplate; } @Bean("urlConnection"

  • SpringBoot RestTemplate 简单包装解析

    RestTemplate设计是为了Spring更好的请求并解析Restful风格的接口返回值而设计的,通过这个类可以在请求接口时直接解析对应的类. 在SpringBoot中对这个类进行简单的包装,变成一个工具类来使用,这里用到的是getForEntity和postForEntity方法,具体包装的代码内容 如下: package cn.eangaie.demo.util; import com.alibaba.fastjson.JSONObject; import org.springframe

  • SpringBoot Security整合JWT授权RestAPI的实现

    本教程主要详细讲解SpringBoot Security整合JWT授权RestAPI. 基础环境 技术 版本 Java 1.8+ SpringBoot 2.x.x Security 5.x JWT 0.9.0 创建项目 初始化项目 mvn archetype:generate -DgroupId=com.edurt.sli.slisj -DartifactId=spring-learn-integration-security-jwt -DarchetypeArtifactId=maven-ar

  • SpringBoot http请求注解@RestController原理解析

    这篇文章主要介绍了SpringBoot http请求注解@RestController原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 @RestController @RestController = @Controller + @ResponseBody组成,等号右边两位同志简单介绍两句,就明白我们@RestController的意义了: @Controller 将当前修饰的类注入SpringBoot IOC容器,使得从该类所在的项目

  • Spring boot2X Consul如何通过RestTemplate实现服务调用

    这篇文章主要介绍了spring boot2X Consul如何通过RestTemplate实现服务调用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Consul可以用于实现分布式系统的服务发现与配置 服务调用有两种方式: A.使用RestTemplate 进行服务调用 负载均衡--通过Ribbon注解RestTemplate B.使用Feign 进行声明式服务调用 负载均衡--默认使用Ribbon实现 先使用RestTemplate来实现 1

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

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

  • Spring Boot通过Junit实现单元测试过程解析

    这篇文章主要介绍了Spring Boot通过Junit实现单元测试过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.需要在pom.xml中引入spring-boot-starter-test <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifa

  • spring boot jar的启动原理解析

     1.前言 近来有空对公司的open api平台进行了些优化,然后在打出jar包的时候,突然想到以前都是对spring boot使用很熟练,但是从来都不知道spring boot打出的jar的启动原理,然后这回将jar解开了看了下,与想象中确实大不一样,以下就是对解压出来的jar的完整分析. 2.jar的结构 spring boot的应用程序就不贴出来了,一个较简单的demo打出的结构都是类似,另外我采用的spring boot的版本为1.4.1.RELEASE网上有另外一篇文章对spring

  • Spring Boot 文件上传原理解析

    首先我们要知道什么是Spring Boot,这里简单说一下,Spring Boot可以看作是一个框架中的框架--->集成了各种框架,像security.jpa.data.cloud等等,它无须关心配置可以快速启动开发,有兴趣可以了解下自动化配置实现原理,本质上是 spring 4.0的条件化配置实现,深抛下注解,就会看到了. 说Spring Boot 文件上传原理 其实就是Spring MVC,因为这部分工作是Spring MVC做的而不是Spring Boot,那么,SpringMVC又是怎么

  • Spring Boot 整合 Shiro+Thymeleaf过程解析

    这篇文章主要介绍了Spring Boot 整合 Shiro+Thymeleaf过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.导包 <!-- springboot 与 shiro 的集成--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <

  • Spring Boot Logback配置日志过程解析

    这篇文章主要介绍了Spring Boot Logback配置日志过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 出于性能等原因,Logback 目前是springboot应用日志的标配: 当然有时候在生产环境中也会考虑和三方中间件采用统一处理方式. 配置时考虑点 支持日志路径,日志level等配置 日志控制配置通过application.yml下发 按天生成日志,当天的日志>50MB回滚 最多保存10天日志 生成的日志中Pattern自

  • Spring Boot启动流程断点过程解析

    这篇文章主要介绍了Spring Boot启动流程断点过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 启动入口 跟进run方法 : 一个用来使用默认的配置从特定的源运行SpringApplication的静态帮助类. 这个类有两个重载方法,另一个用来传入多个源.通常,单个参数方法是数组方法的一个特例 创建一个新的SpringApplication实例.这个应用程序上下文会从特定的源加载Beans,这个实例会在调用run方法之前被定制化.

  • spring boot 2整合swagger-ui过程解析

    这篇文章主要介绍了spring boot 2整合swagger-ui过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.添加mvn依赖 修改pom.xml加入 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.5.0</v

  • Spring Boot定时+多线程执行过程解析

    这篇文章主要介绍了Spring Boot定时+多线程执行过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Spring Boot 定时任务有多种实现方式,我在一个微型项目中通过注解方式执行定时任务. 具体执行的任务,通过多线程方式执行,单线程执行需要1小时的任务,多线程下5分钟就完成了. 执行效率提升10倍以上,执行效率提升10倍以上,执行效率提升10倍以上. 重要的事情说三遍! 本文不深入介绍具体的原理,大家如果要实现类似的功能,只需要

  • Spring Boot使用过滤器Filter过程解析

    这篇文章主要介绍了Spring Boot使用过滤器Filter过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 首先我们说说什么是过滤器,过滤器是对数据进行过滤,预处理过程,当我们访问网站时,有时候会发布一些敏感信息,发完以后有的会用*替代,还有就是登陆权限控制等,一个资源,没有经过授权,肯定是不能让用户随便访问的,这个时候,也可以用到过滤器.过滤器的功能还有很多,例如实现URL级别的权限控制.压缩响应信息.编码格式等等. 过滤器依赖se

随机推荐