MockMvc

注意点

1、通过spring上下文获取mockmvc对象

@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

2、json处理

通过MockMvc发送和接受请求都是json。

所以发送请求的时候,需要将javabean转json

.content(new ObjectMapper().writeValueAsString(person)).contentType(MediaType.APPLICATION_JSON))

在接受得到result后,也需用json串转javabean。

Person person = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class);

code

待测试的controller

package com.lexiaoyao.mocktest.controller;

import com.lexiaoyao.mocktest.model.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; @RestController
@RequestMapping("test")
@Slf4j
public class TestController { //通过正则限时id只能为数字
@GetMapping("/person/{id:\\d+}")
public ResponseEntity getPerson(@PathVariable("id") Integer id) {
return ResponseEntity.ok(new Person(id, "tom", 22));
} @PostMapping("/person")
public ResponseEntity postPerson(@RequestBody Person person) {
return ResponseEntity.ok(person);
} }

测试类


@SpringBootTest
@Slf4j
class MocktestApplicationTests { private MockMvc mockMvc; @Autowired
private WebApplicationContext webApplicationContext; //在junit5内用BeforeEach代替Before
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
} @Test
public void testGet() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/person/1")
//设置以json方式传输
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn(); //将MvcResult中的response转为对象
Person person = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class);
Assert.assertNotNull(person);
Assert.assertEquals(person.getId(), Integer.valueOf(1));
} @Test
public void testPost() throws Exception {
Person person = new Person(10, "name", 2);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/test/person")
.content(new ObjectMapper().writeValueAsString(person)).contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
Person resultPerson = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class);
Assert.assertNotNull(person);
Assert.assertEquals(person.getId(), resultPerson.getId());
} }

github

https://github.com/lexiaoyao1995/mock_mvc

MockMvc编写单测的更多相关文章

  1. 使用Groovy+Spock轻松写出更简洁的单测

    当无法避免做一件事时,那就让它变得更简单. 概述 单测是规范的软件开发流程中的必不可少的环节之一.再伟大的程序员也难以避免自己不犯错,不写出有BUG的程序.单测就是用来检测BUG的.Java阵营中,J ...

  2. 使用Java函数接口及lambda表达式隔离和模拟外部依赖更容易滴单测

    概述 单测是提升软件质量的有力手段.然而,由于编程语言上的支持不力,以及一些不好的编程习惯,导致编写单测很困难. 最容易理解最容易编写的单测,莫过于独立函数的单测.所谓独立函数,就是只依赖于传入的参数 ...

  3. 【spock】单测竟然可以如此丝滑

    0. 为什么人人都讨厌写单测 在之前的关于swagger文章里提到过,程序员最讨厌的两件事,一件是别人不写文档,另一件就是自己写文档.这里如果把文档换成单元测试也同样成立. 每个开发人员都明白单元测试 ...

  4. 输入输出无依赖型函数的GroovySpock单测模板的自动生成工具(上)

    目标 在<使用Groovy+Spock轻松写出更简洁的单测> 一文中,讲解了如何使用 Groovy + Spock 写出简洁易懂的单测. 对于相对简单的无外部服务依赖型函数,通常可以使用 ...

  5. Allure对单测结果以及robotframework结果的处理

    Allure对单测结果以及robotframework结果的处理 Allure只能针对pytest的单测结果生成相应的报告: 如果需要对unittest的测试框架结果进行展示,可以使用pytest执行 ...

  6. 你真的会写单测吗?TDD初体验

    前言: 昨天读到了一篇文章,讲的是TDD,即Test-Driven Development,测试驱动开发.大体意思是,它要求在编写某个功能的代码之前先编写测试代码,然后只编写使测试通过的功能代码,通过 ...

  7. C# Ping的例子,可用于测试网络,延迟xx毫秒 C#编写网站测速

    C#编写网站测速 WebClient wcl = new WebClient(); Stopwatch spwatch = new Stopwatch(); spwatch.Start(); byte ...

  8. Java 单测 回滚

    Java 在单测的时候 需要做回滚 设置如下: 需要添加以下 注解 在类上 defaultRollback = true : 为 默认全部回滚 defaultRollback = false : 为 ...

  9. Swift中编写单例的正确方式

    在之前的帖子里聊过状态管理有多痛苦,有时这是不可避免的.一个状态管理的例子大家都很熟悉,那就是单例.使用Swift时,有许多方法实现单例,这是个麻烦事,因为我们不知道哪个最合适.这里我们来回顾一下单例 ...

随机推荐

  1. 当你的系统依赖于某个bug...

    标题粗略看是有点违反常识的,bug通常是指某些代码存在问题导致系统没有按照期望方式工作,应该是需要尽可能被修复的,这样系统才会正常工作.但是,开发实践中会发现在某些情况下,本来功能没有问题,在你信心满 ...

  2. Linux中C++提示‘close’ was not declared

    C++socket编程时关闭socket和epoll时出现‘close’ was not declared,是程序头文件缺失导致的.缺失头文件#include <unistd.h>

  3. C#LeetCode刷题之#263-丑数(Ugly Number)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3862 访问. 编写一个程序判断给定的数是否为丑数.丑数就是只包含 ...

  4. LeetCode198 House Robber(打家劫舍)

    题目 You are a professional robber planning to rob houses along a street. Each house has a certain amo ...

  5. [C/C++]快速读入代码(快读)

    快读 1.为什么要有快读 好吧,有些题目看上去十分简单,例如https://www.luogu.com.cn/problem/P4305这道题,实际上数据量巨多,光是一个测试点就可能有几个MB,在这种 ...

  6. JS实例-DOM查询

    <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" ...

  7. HTML基础-06

    网页背景 1.  设置背景颜色          background-color:#bfa; 设置背景图片               background-image:url(“./img/... ...

  8. python基本数据类型(—)

    数字 int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位系统上,整数的位数为64位,取值范围为-2** ...

  9. 【原创】Linux虚拟化KVM-Qemu分析(一)

    背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: KVM版本:5.9 ...

  10. Uni-app从入门到实战

    前言 uni-app是一个使用vue.js开发跨平台应用的前端框架,开发者只需要编写一套代码,便可以发布到IOS.Android和微信小程序等多个平台.所以我打算学习下这个框架,快速浏览了一遍官网之后 ...