对于类的测试,可以有很多的方式进行实现,比如可以使用PostMan,使用HttpClient请求等,这里主要讲的是MockMcv的测试

一:引入依赖

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

  

二:Demo如下:

package cn.wangtao.controller;

import cn.wangtao.HTTPEntity.RequestEntity.TestRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import java.util.HashMap;
import java.util.Map; @RunWith(SpringRunner.class)
@SpringBootTest(classes = cn.wangtao.run.Application.class)//注意这里的类要引入的是Main入口类
public class TestControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private ObjectMapper objectMapper=new ObjectMapper(); @Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); //构造MockMvc
} @Test
public void testModelParam() throws Exception {
TestRequest request = new TestRequest();
request.setAge(18);
request.setName("桃子");
request.setAddress("上海");
request.setServerType("ctr1");
Map<String, String> map = new HashMap<String, String>();
map.put("request",objectMapper.writeValueAsString(request));
modelParam("/test",objectMapper.writeValueAsString(request));
} @Test
public void testMoreParam() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("name","wangtao");
map.put("age","18");
map.put("address","上海");
map.put("serverType","ctr2");
moreParam("/test2",map);
} /**
* @Author wangtao
* @Description 对象模型接收
* @Date 2019-3-28 18:01
* @Param param:对象的json 结构
* @return
**/
public void modelParam(String requestPath, String param ) throws Exception {
MockHttpServletRequestBuilder mockHttpServletRequestBuilder
= MockMvcRequestBuilders.get(requestPath)//自己选择方式
.content(param)
.contentType(MediaType.APPLICATION_JSON_UTF8);
MvcResult result=mockMvc.perform(mockHttpServletRequestBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
int statusCode = result.getResponse().getStatus();
String content = result.getResponse().getContentAsString();
System.out.println("statusCode: "+statusCode);
System.out.println("返回结果 content: "+content);
Assert.assertEquals(statusCode, 200);
} /**
* @Author wangtao
* @Description 一个或多个k-参数
* @Date 2019-3-28 17:59
* @Param requestPath:URI, map:参数集合
* @return
**/
public void moreParam(String requestPath, Map<String,String> map ) throws Exception {
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(requestPath);//请求方式自己定
//参数封装
for (Map.Entry<String,String> entry:map.entrySet() ){
mockHttpServletRequestBuilder.param(entry.getKey(),entry.getValue());
}
mockHttpServletRequestBuilder.contentType(MediaType.APPLICATION_JSON_UTF8);
MvcResult result=mockMvc.perform(mockHttpServletRequestBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
int statusCode = result.getResponse().getStatus();
String content = result.getResponse().getContentAsString();
System.out.println("statusCode: "+statusCode);
System.out.println("返回结果 content: "+content);
Assert.assertEquals(statusCode, 200);
} }

  

SpringBoot MockMvc的单元测试的更多相关文章

  1. 【快学springboot】在springboot中写单元测试[Happyjava]

    前言 很多公司都有写单元测试的硬性要求,在提交代码的时候,如果单测通不过或者说单元测试各种覆盖率不达标,会被拒绝合并代码.写单元测试,也是保证代码质量的一种方式. junit单元测试 相信绝大多数的J ...

  2. 【快学springboot】在springboot中写单元测试

    前言 很多公司都有写单元测试的硬性要求,在提交代码的时候,如果单测通不过或者说单元测试各种覆盖率不达标,会被拒绝合并代码.写单元测试,也是保证代码质量的一种方式. junit单元测试 相信绝大多数的J ...

  3. springboot Service层单元测试

    两个实现类实现同一个Service接口 public interface CustomUrlService { List<ShopMetrics> getShopMetrics(); } ...

  4. springboot+mybatis整合(单元测试,异常处理,日志管理,AOP)

    我用的事IDEA,jdk版本是1.7.新建项目的时候这个地方的选择需要注意一下,springboot版本是1.5的,否则不支持1.7的jdk pom.xml <dependency> &l ...

  5. SpringBoot使用Junit4单元测试

    SpringBoot2.0笔记 本篇介绍Springboot单元测试的一些基本操作,有人说一个合格的程序员必须熟练使用单元测试,接下来我们一起在Springboot项目中整合Junit4单元测试. 本 ...

  6. Java程序员的日常—— POI与JDBC、Mockmvc与单元测试

    周日没怎么休息好,周一一天都迷迷糊糊的,不过还算是干了不少的活. 总结一下,大致有以下几点内容: 1 使用poi以及mysql jdbc实现了一个复杂excel的导入 2 基于工程原有的代码,书写sp ...

  7. springboot~mockMvc和asciidoctor生成基于TDD的API文档

    API文档是前端与后端快速开发,减少沟通成本的必要条件,有一份完善的文档是很必要的,由通过测试来生成文档的好处就是:测试数据有了,测试返回结果有了,而且可以对这些字段进行说明,很清晰,在springb ...

  8. spring-boot 速成(11) - 单元测试

    一.添加依赖项: testCompile 'org.springframework.boot:spring-boot-starter-test:1.5.2.RELEASE' 二.单元测试代码示例 im ...

  9. 【SpringBoot】SpringBoot配置与单元测试(二)

    SpringBoot项目创建参考[SpringBoot]SpringBoot快速入门(一) 本文介绍SpringBoot项目的POM文件.配置与单元测试 POM文件 1.SpringBoot的pom文 ...

随机推荐

  1. markdown字体或者图片居中

    1.图片居中实例: 图片居中效果: 2.文字居中实例: 文字居中效果: 你的名字

  2. 详解sizeof与strlen

    一,sizeof是C语言的一种单目运算符,与C语言的其他运算符++,--一样,它并不是函数:sizeof()以字节为单位给出了操作数的大小:sizeof的值是无符号int. strlen是一个函数,只 ...

  3. Elasticsearch 5 Ik+pinyin分词配置详解

    版权声明:本文为博主原创文章,地址:http://blog.csdn.net/napoay,转载请留言. 一.拼音分词的应用 拼音分词在日常生活中其实很常见,也许你每天都在用.打开淘宝看一看吧,输入拼 ...

  4. 获取指定订阅下所有Azure ARM虚拟机配置(CPU核数,内存大小,磁盘信息)的使用情况

    脚本内容: <# .SYNOPSIS This script grab all ARM VM VHD file in the subscription and caculate VHD size ...

  5. QuantLib 金融计算——数学工具之随机数发生器

    目录 QuantLib 金融计算--数学工具之随机数发生器 概述 伪随机数 正态分布(伪)随机数 拟随机数 HaltonRsg SobolRsg 两类随机数的收敛性比较 如果未做特别说明,文中的程序都 ...

  6. TX2 用文件IO的方式操作GPIO

    概述 通过 sysfs 方式控制 GPIO,先访问 /sys/class/gpio 目录,向 export 文件写入 GPIO 编号,使得该 GPIO 的操作接口从内核空间暴露到用户空间,GPIO 的 ...

  7. Mac 10.12安装FTP工具FileZilla

    说明:在Windows估计用的比较多,在Linux基本不用了,CRT和Xshell基本可以完成上传. 下载: (链接: https://pan.baidu.com/s/1bpaxmeN 密码: uuw ...

  8. RHCE 共享文件系统

    9.1 共享文件系统 概述: 共享文件系统通常有两种方式: 基于文件共享,一种直接共享文件夹给client端,常见的技术有NFS(Network File System )和 SMB (Server ...

  9. FAQ of db2fmp messages in the db2diag.log

    http://www-01.ibm.com/support/docview.wss?uid=swg21470035 Technote (FAQ) Question What do these mess ...

  10. mongo 授权访问

    1.授权远程也可以访问 - 首先修改mongodb的配置文件 让其监听所有外网ip 编辑文件:/etc/mongodb.conf 修改后的内容如下: bind_ip = 0.0.0.0 port = ...