SpringBoot MockMvc的单元测试
对于类的测试,可以有很多的方式进行实现,比如可以使用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的单元测试的更多相关文章
- 【快学springboot】在springboot中写单元测试[Happyjava]
前言 很多公司都有写单元测试的硬性要求,在提交代码的时候,如果单测通不过或者说单元测试各种覆盖率不达标,会被拒绝合并代码.写单元测试,也是保证代码质量的一种方式. junit单元测试 相信绝大多数的J ...
- 【快学springboot】在springboot中写单元测试
前言 很多公司都有写单元测试的硬性要求,在提交代码的时候,如果单测通不过或者说单元测试各种覆盖率不达标,会被拒绝合并代码.写单元测试,也是保证代码质量的一种方式. junit单元测试 相信绝大多数的J ...
- springboot Service层单元测试
两个实现类实现同一个Service接口 public interface CustomUrlService { List<ShopMetrics> getShopMetrics(); } ...
- springboot+mybatis整合(单元测试,异常处理,日志管理,AOP)
我用的事IDEA,jdk版本是1.7.新建项目的时候这个地方的选择需要注意一下,springboot版本是1.5的,否则不支持1.7的jdk pom.xml <dependency> &l ...
- SpringBoot使用Junit4单元测试
SpringBoot2.0笔记 本篇介绍Springboot单元测试的一些基本操作,有人说一个合格的程序员必须熟练使用单元测试,接下来我们一起在Springboot项目中整合Junit4单元测试. 本 ...
- Java程序员的日常—— POI与JDBC、Mockmvc与单元测试
周日没怎么休息好,周一一天都迷迷糊糊的,不过还算是干了不少的活. 总结一下,大致有以下几点内容: 1 使用poi以及mysql jdbc实现了一个复杂excel的导入 2 基于工程原有的代码,书写sp ...
- springboot~mockMvc和asciidoctor生成基于TDD的API文档
API文档是前端与后端快速开发,减少沟通成本的必要条件,有一份完善的文档是很必要的,由通过测试来生成文档的好处就是:测试数据有了,测试返回结果有了,而且可以对这些字段进行说明,很清晰,在springb ...
- spring-boot 速成(11) - 单元测试
一.添加依赖项: testCompile 'org.springframework.boot:spring-boot-starter-test:1.5.2.RELEASE' 二.单元测试代码示例 im ...
- 【SpringBoot】SpringBoot配置与单元测试(二)
SpringBoot项目创建参考[SpringBoot]SpringBoot快速入门(一) 本文介绍SpringBoot项目的POM文件.配置与单元测试 POM文件 1.SpringBoot的pom文 ...
随机推荐
- mysql 批量更新的四种方法
批量更新的方法: 1 ) 逐条更新 代码如下: UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value'; 如果更新 ...
- Prim算法---最小生成树
最小生成树的Prim算法也是贪心算法的一大经典应用.Prim算法的特点是时刻维护一棵树,算法不断加边,加的过程始终是一棵树. Prim算法过程: 一条边一条边地加, 维护一棵树. 初始 E = {}空 ...
- 【OCP题库】最新CUUG OCP 12c 071考试题库(68题)
68.(29-13)choose two: Which two statements are true? (Choose two.) A) DICTIONARY is a view that cont ...
- 【ocp-12c】最新Oracle OCP-071考试题库(44题)
44.(9-12)choose all that apply View the Exhibit and examine the details of the ORDER_ITEMS table. Ev ...
- “全栈2019”Java多线程第九章:判断线程是否存活isAlive()详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...
- Mac上使用oh-my-zsh+iterm2
一.安装oh-my-zsh插件 1.1 下载 git clone git://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh 1.2创建新配置 如 ...
- wireshark 1.10.0 编译 及 协议解析部分的一些变化
wireshark不久前升级到1.10.0稳定版,这个版本正如其版本号一样,相比1.8.x有较大变化. 我们先说说在windows下编译的问题,1.8.4/1.8.6版本的编译见我的文章:http:/ ...
- 人工鱼群算法超详细解析附带JAVA代码
01 前言 本着学习的心态,还是想把这个算法写一写,给大家科普一下的吧. 02 人工鱼群算法 2.1 定义 人工鱼群算法为山东大学副教授李晓磊2002年从鱼找寻食物的现象中表现的种种移动寻觅特点中得到 ...
- WampServer访问出现403forbidden的问题解决
1,软件装上以后出现所有服务运行,80端口未被占用的情况下服务器一直处于离线状态 解决方案如下: 网络上面很多教程多说切换服务器为在线状态即可,但是我发现我的菜单里面并没有,用命令又嫌麻烦 在图表上面 ...
- Service Discovery protocol(SDP)
locating services provided by Volume 3 , Part C , section 8 2.1sdp client-server architecture 2.2 se ...