Springboot中使用Junit5和Mockito

  • 使用方法
    • 环境配置
    • 用例配置
    • Mockito使用
  • 常用Mockito功能参考
  • Mockito使用错误记录
    • 参数检验时原始参数与检验参数混用
  • 参考

如果不关心Junit5和Mockito的,直接看使用方法

使用方法

环境配置

使用的是springboot版本为2.3.3.RELEASE,spring-boot-starter-test自带了 mockito-core,因此只需要在pom.xml中引入spring-boot-starter-test,即可使用junit5(即Junit Jupiter):

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

用例配置

通过使用@ExtendWith(MockitoExtension.class)后,相当于在@BeforeEach调用MockitoAnnotations.initMocks(this),

Mockito使用

然后即可在测试类中使用注解@InjectMocks和@Mock注入对象,在方法中使用常用Mockito功能进行测试了

测试类:


import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;@ExtendWith(MockitoExtension.class)
class ServiceImplTest {@Mockprivate IOtherService otherService;@InjectMocksprivate ServiceImpl service;@Testpublic void xxxTest() {//使用when对depdService方法进行模拟,使用eq、anyString对参数进行检验,使用threnReturn返回结果when(otherService.doSomething(eq("参数"), anyString())).thenReturn("xxxx");assertEquals("xxxx", service.doSomething("参数"));verify(otherService).doSomething(eq("参数"), anyString());//直接使用原始值when(otherService.doSomething("参数1", "参数1aaa")).thenReturn("xxxx1");assertEquals("xxxx1", service.doSomething("参数1"));verify(otherService).doSomething("参数1", "参数1aaa");clearInvocations(otherService);//清除之前的调用assertNull(service.doSomething(""));//检测未被调用verifyNoInteractions(otherService);}}

其他服务类:

import org.springframework.beans.factory.annotation.Autowired;public class ServiceImpl {@Autowiredprivate IOtherService otherService;public String doSomething(String param) {if (param.isEmpty()) {return null;}return otherService.doSomething(param, param + "aaa");}
}public interface IOtherService {String doSomething(String param1, String param2);
}

常用Mockito功能参考

功能 参考文档
模拟方法(行为打桩) 2. How about some stubbing?
参数匹配 3. Argument matchers?
调用次数验证 4. Verifying exact number of invocations / at least x / never
模拟void方法的异常 5. Stubbing void methods with exceptions
按顺序验证 6. Verification in order
验证未被调用 7. Making sure interaction(s) never happened on mock
验证多余的调用 8. Finding redundant invocations
@Mock注解创建模拟对象 - 9. Shorthand for mocks creation - @Mock annotation
链式模拟 10. Stubbing consecutive calls (iterator-style stubbing)
doReturn() doThrow()
真实对象部分mock 13. Spying on real objects
更改未存根调用的默认返回值 14. Changing default return values of unstubbed invocations (Since 1.7)
捕获参数后再断言 15. Capturing arguments for further assertions (Since 1.8.0)
真正的部分模拟(模拟对象调用真实对象) 16. Real partial mocks (Since 1.8.0)
可序列化模拟 20. Serializable mocks (Since 1.8.1)
新注解:@Captor, @Spy, @InjectMocks 21. New annotations: @Captor, @Spy, @InjectMocks (Since 1.8.3)
超时验证 22. Verification with timeout (Since 1.8.5)
@Spies和@InjectMocks注解 23. Automatic instantiation of @Spies, @InjectMocks and constructor injection goodness (Since 1.9.0)
一行代码同时创建与模拟 24. One-liner stubs (Since 1.9.0)
忽略验证 25. Verification ignoring stubs (Since 1.9.0)
将调用委托给真实实例 27. Delegate calls to real instance (Since 1.9.5)
监视或模拟抽象类 30. Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)
Mockito 模拟可以跨类加载器序列化/反序列化 31. Mockito mocks can be serialized / deserialized across classloaders (Since 1.10.0)
更好的泛型支持 32. Better generic support with deep stubs (Since 1.10.0)
Mockito JUnit 规则 33. Mockito JUnit rule (Since 1.10.17)
自定义验证失败消息 35. Custom verification failure message (Since 2.1.0)
Java 8 Lambda 匹配器支持 36. Java 8 Lambda Matcher Support (Since 2.1.0)
Java 8 自定义答案支持 37. Java 8 Custom Answer Support (Since 2.1.0)
元数据和泛型类型保留 38. Meta data and generic type retention (Since 2.1.0)
模拟final类、枚举和final方法 39. Mocking final types, enums and final methods (Since 2.1.0)
新的 JUnit Jupiter (JUnit5+) 扩展 45. New JUnit Jupiter (JUnit5+) extension
新的Mockito.lenient()和MockSettings.lenient()方法 46. New Mockito.lenient() and MockSettings.lenient() methods (Since 2.20.0)
用于模拟静态方法的新 API 48. New API for mocking static methods (Since 3.4.0)
用于模拟对象构造的新 API 49. New API for mocking object construction (Since 3.5.0)
避免代码生成将模拟限制为接口时 50. Avoiding code generation when restricting mocks to interfaces (Since 3.12.2)

Mockito使用错误记录

参数检验时原始参数与检验参数混用

错误代码:

when(otherService.doSomething("参数", anyString())).thenReturn("xxxx1");

错误提示:

This exception may occur if matchers are combined with raw values://incorrect:someMethod(anyObject(), "raw String");

错误原因:方法参数未正确使用
正确代码:

when(otherService.doSomething(eq("参数"), anyString())).thenReturn("xxxx1");

参考

  • Mockito文档
  • SpringBoot 单元测试详解
  • JUnit 5中扩展模型的深入理解

Springboot中使用Junit5(Jupiter)和Mockito相关推荐

  1. SpringBoot教程(13) JUnit5详解 常用注解 BeforeEach BeforeAll ParameterizedTest RepeatedTest

    JUnit5详解 常用注解 BeforeEach BeforeAll ParameterizedTest RepeatedTest 一.前言 1. 引入test包 二.注解 三.测试案例 1. @Be ...

  2. java 单元测试_在springboot中写单元测试解决依赖注入和执行后事务回滚问题

    往期文章 「Java并发编程」谈谈Java中的内存模型JMM 面试官:说说你知道多少种线程池拒绝策略 为什么不要在MySQL中使用UTF-8编码方式 前言 很多公司都有写单元测试的硬性要求,在提交代码 ...

  3. springboot 事务嵌套问题_在springboot中写单元测试解决依赖注入和执行后事务回滚问题...

    往期文章 「Java并发编程」谈谈Java中的内存模型JMM 面试官:说说你知道多少种线程池拒绝策略 为什么不要在MySQL中使用UTF-8编码方式 前言 很多公司都有写单元测试的硬性要求,在提交代码 ...

  4. SpringBoot中yaml配置

    yaml是一种可读性高,用来表示数据序列化的格式.在SpringBoot中也可以使用properties,但是推荐使用yaml. 在SpringBoot中使用一种全局的配置文件,其名称是固定的为app ...

  5. SpringBoot中集成Redis实现对redis中数据的解析和存储

    场景 SpringBoot中操作spring redis的工具类: SpringBoot中操作spring redis的工具类_霸道流氓气质的博客-CSDN博客 上面讲的操作redis的工具类,但是对 ...

  6. W2-2:在Maven项目中进行Junit5单元测试

    系列文章目录 W2-1:Maven引入外部依赖--以GSON的使用为例 W2-2:在Maven项目中进行Junit5单元测试 - 环境:IntelliJ IDEA Community Edition ...

  7. 在SpringBoot中使用Spring Session解决分布式会话共享问题

    在SpringBoot中使用Spring Session解决分布式会话共享问题 问题描述: 每次当重启服务器时,都会导致会员平台中已登录的用户掉线.这是因为每个用户的会话信息及状态都是由session ...

  8. SpringBoot 中 JPA 的使用

    前言 第一次使用 Spring JPA 的时候,感觉这东西简直就是神器,几乎不需要写什么关于数据库访问的代码一个基本的 CURD 的功能就出来了.下面我们就用一个例子来讲述以下 JPA 使用的基本操作 ...

  9. 难以想象SpringBoot中的条件注解底层居然是这样实现的

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源 | https://urlify.cn/bm2qqi Spr ...

  10. 面试:SpringBoot中的条件注解底层是如何实现的?

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源 | https://urlify.cn/bm2qqi Spr ...

最新文章

  1. 专题 13 IPC之信号量
  2. spring-boot-devtools
  3. CSS 居中方法集锦
  4. Flutter获取随机数 Dart语言核心基础
  5. 如何才能成为一个成功的项目经理
  6. css3 选择器_IT兄弟连 HTML5教程 CSS3揭秘 CSS3概述
  7. Qt TextEdit 使用 (积累中....)
  8. Redis笔记(六)Redis的消息通知
  9. 基于Cocos2d-x开发guardCarrot--4 《保卫萝卜2》主页面动画
  10. jieba分词工具的使用-python代码
  11. 首推机器人视觉解决方案 百度AI开发者实战营成都站揭秘
  12. c# 模拟串口通信 SerialPort
  13. Maxscale读写分离,多实例
  14. 生成随机数字字母组合参数
  15. 公司企业邮箱登陆客户端,邮件服务器如何设置?
  16. 计算机应用基础蓝色方框在哪,word段落设置3磅蓝色单线边框并加底纹怎...
  17. R语言中调用windows中的字体方法
  18. 【小组作业】电影院管理系统
  19. CSS - 实现Loading加载动画
  20. FastAPI--路由(2)

热门文章

  1. 基于MATLAB的有源三相滤波器的设计,基于MATLAB的有源滤波器的设计与仿真
  2. 西门子界面官方精美触摸屏+WINCC程序模板 西门子官方触摸屏程序模板,炫酷的扁平式动画效果
  3. matlab随机抽样模拟,随机抽样一致性算法(matlab)
  4. 1 Spark机器学习 spark MLlib 入门
  5. 安装最好用的计算机软件,装机软件哪个好?教您最好的装机软件推荐
  6. 硬时间窗 遗传算法 matlab,基于遗传算法的多种运输工具或带时间窗的路径优化问题(VRP)的求解(MATLAB)...
  7. VS社区版许可证过期更新
  8. windows datacenter 2012 R2 密钥
  9. win10易升_白嫖性能!Win10系统开启硬件加速GPU调度计划提升显卡性能的方法
  10. 2021年PMP考试模拟题3(含答案)