Mockito 结合 Springboot 进行应用测试
Spring Boot可以和大部分流行的测试框架协同工作:通过Spring JUnit创建单元测试;生成测试数据初始化数据库用于测试;Spring Boot可以跟BDD(Behavier Driven Development)工具、Cucumber和Spock协同工作,对应用程序进行测试。
在web应用程序中,我们主要是对Service层做单元测试,以前单元测试都是使用 junit4 ,对Controller层做集成测试或者接口测试,对Controller层的测试一般有两种方法:(1)发送http请求;(2)模拟http请求对象。
第一种方法需要配置回归环境,通过修改代码统计的策略来计算覆盖率;第二种方法是比较正规的思路。
Mockito网上相关的文档不是很多,基本都是入门性质的没有更深层次的使用案例,而且Mockito本身功能也在不断的完善,导致写起来比较费劲,好多地方完全靠猜。摸索之下算是完成了,把踩过的坑记录一下,万一有人需要呢。
下面我将演示如何用Mock对象测试Service、Controller层的代码。
引入相关jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
项目使用的是 springboot 2.4.0。
spring-boot-starter-test 中包含 junit5 和 Mockito 相关jar。无需额外引入。
如果想使用 junit4,可以将springboot版本降低,junit4 与 junit5 在一些注解和方法上有区别,比如注解的引入目录不同,一些方法进行了优化,有兴趣可以查阅相关资料,这里就不再赘述。
下面代码是 junit5 使用样式。
项目目录结构如下

Controller类
@RestController
@RequestMapping("/api/v1")
public class UserController { @Autowired
UserService userService; @GetMapping("user/{userId}")
public User say(@PathVariable("userId") Long id) {
return userService.getUser(id);
} @PostMapping("user/edit")
public User edit(@RequestBody User user) {
return userService.edit(user);
}
}
Service 实现类
@Service
public class UserServiceImpl implements UserService { @Autowired
UserDao userDao; @Override
public User getUser(Long id) {
return userDao.getUser(id);
} @Override
public User edit(User user) {
return userDao.edit(user);
}
}
Dao 接口
public interface UserDao {
User getUser(Long id);
User edit(User user);
}
User 类
public class User {
private Long id;
private String name;
private String desc;
get()...
set()...
toString()...
}
UserDao 是一个接口,没有任何的相关实现。所以对该接口进行mock。测试代码如下
package com.mmling.mockitodemo;
import com.mmling.mockitodemo.controller.UserController;
import com.mmling.mockitodemo.dao.UserDao;
import com.mmling.mockitodemo.entity.User;
import com.mmling.mockitodemo.service.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Robert
* @date 2020-11-27 14:38
*/
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = MockitoDemoApplication.class)
public class UserBeanTest {
@Autowired
UserController controller;
@Autowired
UserService userService;
@MockBean //需要mock的bean,会自动注入到调用的对象中
private UserDao userDao;
MockMvc mockMvc;
/**
* 测试 service 层
*/
@Test
public void test() {
// 定义未实现的 service 返回
when(userDao.getUser(anyLong())).thenReturn(new User(anyLong(), "张三", "路人"));
System.out.println(userService.getUser(12L).toString());
verify(userDao, times(1)).getUser(anyLong());
}
/**
* 测试 controller 时,需要构建 mvc 环境
*/
@BeforeEach
public void setup() {
//构建mvc环境
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
/**
* .perform() : 执行一个MockMvcRequestBuilders的请求;MockMvcRequestBuilders有.get()、.post()、.put()、.delete()等请求。
* .andDo() : 添加一个MockMvcResultHandlers结果处理器,可以用于打印结果输出(MockMvcResultHandlers.print())。
* .andExpect : 添加MockMvcResultMatchers验证规则,验证执行结果是否正确。
*/
@Test
public void testGetUser() throws Exception {
// 定义未实现的 service 返回
when(userDao.getUser(anyLong())).thenReturn(new User(12L, "张三", "路人"));
//模拟接口调用
ResultActions perform = this.mockMvc.perform(get("/api/v1/user/12"));
//对接口响应进行验证
perform.andExpect(status().isOk())
.andExpect(content().json("{id:12,name:张三,desc:路人}")); // 可以不用写成转义后的json格式
System.out.println(perform.andReturn().getResponse().getContentAsString());
}
@Test
public void testEditUser() throws Exception {
// 定义未实现的 service 返回
when(userDao.edit(any(User.class))).thenReturn(new User(12L, "张三", "路人"));
//模拟接口调用
ResultActions perform = this.mockMvc.perform(post("/api/v1/user/edit")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\":12,\"name\":\"张三\",\"desc\":\"路人\"}")); // 必须写成转义后的json格式,否则没法转换
//对接口响应进行验证
perform.andExpect(status().isOk())
.andExpect(content().json("{id:12,name:张三,desc:路人}")); // 可以不用写成转义后的json格式
System.out.println(perform.andReturn().getResponse().getContentAsString());
}
}
注意:
1.由于这是Spring Boot的测试,因此我们可通过@Autowired注解织入任何由Spring管理的对象,或者是通过@Value设置指定的环境变量的值。
2.每个测试用例用@Test注解修饰。
3.第一个测试用中展示了如何测试 Service 层代码
4.第二个第三个测试用例中展示了如何通过MockMvc对象实现对RESTful URL接口订单查询的测试。Spring测试框架提供MockMvc对象,可以在不需要客户端-服务端请求的情况下进行MVC测试,完全在服务端这边就可以执行Controller的请求,跟启动了测试服务器一样。
5.测试开始之前需要建立测试环境,setup方法被@Before修饰。通过MockMvcBuilders工具,使用 controller 对象作为参数,创建一个MockMvc对象。
6. mockMvc 可以链式调用,进行接口调用,并判断状态
//模拟接口调用
ResultActions perform = this.mockMvc.perform(get("/api/v1/user/12"))
.andExpect(status().isOk())
.andExpect(content().json("{id:12,name:张三,desc:路人}")); // 可以不用写成转义后的json格式
7. content().json() 会对结果进行处理,所以判断的无需转义,但 this.mockMvc.perform(post("/api/v1/user/edit").contentType(MediaType.APPLICATION_JSON).content() 中的json是需要手动转义的。
Mockito 结合 Springboot 进行应用测试的更多相关文章
- 0109 springboot的部署测试监控
springboot的部署测试监控 部署 基于maven 打包 JAR 打包方式一般采用的jar包,使用springboot的默认方式即可: 使用maven命令: mvn clean package ...
- Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用
==============Springboot的日志管理============= springboot无需引入日志的包,springboot默认已经依赖了slf4j.logback.log4j等日 ...
- SpringBoot整合Swagger测试api构建
@Author:SimpleWu 什么是Swagger? Swagger是什么:THE WORLD'S MOST POPULAR API TOOLING 根据官网的介绍: Swagger Inspec ...
- springboot集成junit测试与javamail测试遇到的问题
1.springboot如何集成junit测试? 导入junit的jar包 使用下面注解: @RunWith()关于这个的解释看下这两篇文章: http://www.imooc.com/qadetai ...
- SpringBoot生产/开发/测试多环境的选择
多环境选择 一般一套程序会被运行在多部不同的环境中,比如开发.测试.生产环境,每个环境的数据库地址,服务器端口这些都不经相同,若因为环境的变动而去改变配置的的参数,明显是不合理且易造成错误的 对于不同 ...
- SpringBoot使用Junit测试 防止事物自动回滚
问题:我在测试类中的save方法测试成功通过,但数据库没有插入数据 测试方法如下: @Test @Transactional // @Rollback(false) public voi ...
- springboot利用MockMvc测试controller控制器
主要记录一下控制器的测试,service这些类测试相对简单些(可测试性强) API测试需求比较简单: ① 需要返回正确的http状态码 200 ② 需要返回json数据,并且不能返回未经捕获的系统异常 ...
- Spring-boot非Mock测试MVC,调试启动tomcat容器
平常我们在使用spring-boot去debug一个web应用时,通常会使用MockMvc. 如下配置: @RunWith(value = SpringRunner.class) @SpringBoo ...
- SpringBoot项目的测试类
1. package soundsystem; import static org.junit.Assert.*; import org.junit.Test; import org.junit.ru ...
随机推荐
- Python批量图片识别并翻译——我用python给女朋友翻译化妆品标签
Python批量图片识别并翻译--我用python给女朋友翻译化妆品标签 最近小编遇到一个生存问题,女朋友让我给她翻译英文化妆品标签.美其名曰:"程序猿每天英语开发,英文一定很好吧,来帮我翻 ...
- STM32入门系列-介绍STM32型号与功用
作为STM32初学者,一般会选择购置一块开发板,因为在开发板上有很多已经集成好的模块,如红外模块.按键模块.LED模块.DAC模块.ADC模块.can模块.485模块.以太网模块.WiFi模块.蜂鸣器 ...
- Spring创建Bean的过程Debug
目录 Spring流程Debug 1.1 Spring测试环境搭建 1.2 Debug容器创建过程 1.3 AbstractApplicationContext的refresh()包含的13个方法分析 ...
- python机器学习实现逻辑斯蒂回归
逻辑斯蒂回归 关注公众号"轻松学编程"了解更多. [关键词]Logistics函数,最大似然估计,梯度下降法 1.Logistics回归的原理 利用Logistics回归进行分类的 ...
- [BZOJ 4818/LuoguP3702][SDOI2017] 序列计数 (矩阵加速DP)
题面: 传送门:https://www.lydsy.com/JudgeOnline/problem.php?id=4818 Solution 看到这道题,我们不妨先考虑一下20分怎么搞 想到暴力,本蒟 ...
- MySQL日期函数与日期转换格式化函数大全
Mysql作为一款开元的免费关系型数据库,用户基础非常庞大,本文列出了MYSQL常用日期函数与日期转换格式化函数 1.DAYOFWEEK(date) 1 2 SELECT DAYOFWEEK('201 ...
- 用微信小程序做一个小电商 sku
效果展示图 功能点概述 图一功能点有 搜索 轮播图 商品展示 图二功能点 导航栏 加入购物车 图四功能点 评论点 图五购物车 复选框 ( 全选全不选 ) 即点即改 总计结算 功能详解 1.A(搜索) ...
- phpword读取内容和样式 生成新的内容
table样式还未读出 正在测试中, 目前有 rows cell textrun等样式 顺序不固定 可以设定 <?php require 'vendor/autoload.php'; use P ...
- .NET 5.0正式发布,功能特性介绍(翻译)
本文由葡萄城技术团队翻译并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 我们很高兴今天.NET5.0正式发布.这是一个重要的版本-其中也包括了C# ...
- Sublime Text 3 安装插件与快捷键总结
ublime Text 3 是一个了不起的软件.首先,它是一个干净,实用,可以快速的编写代码编辑器.它不仅具有令人难以置信的内置功能(多行编辑和VIM模式),而且还支持插件,代码片段和其他许多东西.很 ...