对于类的测试,可以有很多的方式进行实现,比如可以使用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. 546. Remove Boxes

    Given several boxes with different colors represented by different positive numbers. You may experie ...

  2. 洛谷P4250 [SCOI2015]小凸想跑步(半平面交)

    题面 传送门 题解 设\(p\)点坐标为\(x_p,y_p\),那么根据叉积可以算出它与\((i,i+1)\)构成的三角形的面积 为了保证\(p\)与\((0,1)\)构成的面积最小,就相当于它比其它 ...

  3. k_means算法的C++实现

    首先画出k_means算法的流程图:

  4. Java8新特性学习笔记(一) Lambda表达式

    没有用Lambda表达式的写法: Comparator<Transaction> byYear = new Comparator<Transaction>() { @Overr ...

  5. day03 --class --homework

    '''# >>>>>>2 :,有字符串s = "123a4b5c"#>>>>>^ 1: # 1)通过对s切片形成新 ...

  6. python基础知识梳理----3基本数据类型,int,bool,str ,for 循环,迭代

    一:python的基本类型 1.int  -----整数,主要进行数学运算 2.str  -----字符串,可以保存少量数据,并进行相关操作, 3. bool ---布尔类型,判断真假 4.list ...

  7. FlowPortal-BPM——离线审批(邮箱审批)配置

    一.将系统文件复制到安装目录下 二.以管理员身份运行bat安装程序 三.开启邮件离线审批服务 四.创建数据库表(JAVA数据库 或 .Net数据库) 五.配置config文件(发件箱.收件箱.错误问题 ...

  8. C. Edgy Trees Codeforces Round #548 (Div. 2) 【连通块】

    一.题面 here 二.分析 这题刚开始没读懂题意,后来明白了,原来就是一个数连通块里点数的问题.首先在建图的时候,只考虑红色路径上的点.为什么呢,因为为了不走红色的快,那么我们可以反着想只走红色的路 ...

  9. 思科设备配置DHCP服务

    路由器,三层交换机都是可以做DHCP服务的,下面以Cisco 3750G-24TS-S为例配置DHCP服务,指令如下: ip dhcp pool DHCP-Server network 192.168 ...

  10. c# 操作excle

    添加引用  Microsoft.Office.Interop.Excel; 添加命名空间 using Excel = Microsoft.Office.Interop.Excel; //创建接口变量- ...