博客
关于我
mock静态方法指引
阅读量:800 次
发布时间:2023-02-09

本文共 3144 字,大约阅读时间需要 10 分钟。

mock静态方法指引

mockito 在3.4.0版本开始支持mock static method

文档:https://wttech.blog/blog/2020/mocking-static-methods-made-possible-in-mockito-3.4.0/

1. 升级Maven依赖

org.mockito
mockito-core
3.6.28
test
org.mockito
mockito-inline
3.6.28
test
org.mockito
mockito-junit-jupiter
3.4.0
test

2. 使用方式

  • 静态方法
public final class MysteryBox {       public static Optional
amaze(String codeWord) { // todo }}
  • 待测试的类,使用了MysteryBox.amaze(String)静态方法
public class HaplessUser {     public Mystery unleashMystery(String magicSpell) {       Optional
om = MysteryBox.amaze(magicSpell); return om.orElseThrow(() -> new FailureToAmazeException("The box was empty")); }}
  • 单元测试类,mock静态方法
@Test@DisplayName("Should throw an exception upon failing to uncover mind-boggling mysteries")void testUncoverMysteries() {     // 1.在try代码块中实例化一个MockedStatic,使用范围仅仅在try代码块内  try (MockedStatic
mb = Mockito.mockStatic(MysteryBox.class)) { // 2. mock静态方法的调用 mb.when(() -> { MysteryBox.amaze(any(String.class )) }) .thenReturn(Optional.empty()); // 3. 调用单元测试方法 assertThrows(FailureToAmazeException.class, () -> subjectUnderTest.unleashMystery("Abracadabra")); } // 静态方法的mock在这里是不可用的}

3. 异常情况

在同个测试类,当多个测试方法都需要mock调用某个静态方法时,代码如下

@ExtendWith(MockitoExtension.class)public class KonfigurationCopyServiceTest {     @InjectMocks	private EKonfigurationCopyServiceImpl konfigurationCopyServiceImpl;		@MockBean	private FileProcessRecordServiceImpl fileProcessRecordService;  @BeforeEach  public void setUp() {       // mock静态方法		MockedStatic
mockSpringUtil = Mockito.mockStatic(SpringUtil.class); mockSpringUtil.when(() -> SpringUtil.getActiveProfile()).thenReturn("dev"); } @Test void test1() { // 省略@Test的单元测试方法 } @Test void test2() { // 省略@Test的单元测试方法 }}

此时,会抛出如下异常信息:

org.mockito.exceptions.base.MockitoException: For xx.xxxx.util.SpringUtil, static mocking is already registered in the current threadTo create a new mock, the existing static mock registration must be deregistered

静态mock已经在当前线程中注册了,要创建新的mock,必须注销现有的静态mock注册

解决方式
  • 导入
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
  • 在测试类上添加注解@TestInstance(PER_CLASS)
  • 使用@BeforeAll代替@BeforeEach
// 添加@TestInstance(PER_CLASS)注解@TestInstance(PER_CLASS)@ExtendWith(MockitoExtension.class)public class KonfigurationCopyServiceTest {     @InjectMocks	private EKonfigurationCopyServiceImpl konfigurationCopyServiceImpl;		@MockBean	private FileProcessRecordServiceImpl fileProcessRecordService;  // 使用@BeforeAll mock静态方法  @BeforeAll  public void setUp() {       // mock静态方法		MockedStatic
mockSpringUtil = Mockito.mockStatic(SpringUtil.class); mockSpringUtil.when(() -> SpringUtil.getActiveProfile()).thenReturn("dev"); } @BeforeEach public void init() { // mock其他方法 } @Test void test1() { // 省略@Test的单元测试方法 } @Test void test2() { // 省略@Test的单元测试方法 }}

转载地址:http://fbffk.baihongyu.com/

你可能感兴趣的文章
Mysql中varchar类型数字排序不对踩坑记录
查看>>
MySQL中一条SQL语句到底是如何执行的呢?
查看>>
MySQL中你必须知道的10件事,1.5万字!
查看>>
MySQL中使用IN()查询到底走不走索引?
查看>>
Mysql中使用存储过程插入decimal和时间数据递增的模拟数据
查看>>
MySql中关于geometry类型的数据_空的时候如何插入处理_需用null_空字符串插入会报错_Cannot get geometry object from dat---MySql工作笔记003
查看>>
mysql中出现Incorrect DECIMAL value: '0' for column '' at row -1错误解决方案
查看>>
mysql中出现Unit mysql.service could not be found 的解决方法
查看>>
mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>
Mysql中各类锁的机制图文详细解析(全)
查看>>
MySQL中地理位置数据扩展geometry的使用心得
查看>>
Mysql中存储引擎简介、修改、查询、选择
查看>>
Mysql中存储过程、存储函数、自定义函数、变量、流程控制语句、光标/游标、定义条件和处理程序的使用示例
查看>>
mysql中实现rownum,对结果进行排序
查看>>
mysql中对于数据库的基本操作
查看>>
Mysql中常用函数的使用示例
查看>>
MySql中怎样使用case-when实现判断查询结果返回
查看>>
Mysql中怎样使用update更新某列的数据减去指定值
查看>>
Mysql中怎样设置指定ip远程访问连接
查看>>
mysql中数据表的基本操作很难嘛,由这个实验来带你从头走一遍
查看>>