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

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

Mockito静态方法指南

升级Maven依赖

为了启用Mockito对静态方法的支持,您需要升级项目的依赖版本。以下是更新后的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

使用方法

静态方法调用

以下是一个简单的示例,展示如何使用Mockito来模拟静态方法:

public class MysteryBox {    public static Optional
mystery(String codeWord) { // 待实现 }}
public class HaplessUser {    public Mystery unleashMystery(String magicSpell) {        Mystery om = MysteryBox.amaze(magicSpell);        return om.orElseThrow(() -> new FailureToAmazeException("The box was empty"));    }}

单元测试类中的静态方法模拟

在单元测试类中,使用Mockito来模拟静态方法:

@Test@DisplayName("应在失败揭开谜团时抛出异常")void testUncoverMysteries() {    try (MockedStatic
mb = Mockito.mockStatic(MysteryBox.class)) { mb.when(() -> MysteryBox.amaze(any(String.class))).thenReturn(Optional.empty()); assertThrows(FailureToAmazeException.class, () -> subjectUnderTest.unleashMystery("Abracadabra")); }}

常见异常及解决方法

在同一个测试类中,多个测试方法可能需要模拟同一个静态方法时,可能会遇到以下异常:

org.mockito.exceptions.base.MockitoException: For xx.xxxx.util.SpringUtil, static mocking is already registered in the current thread

解决方法

为了解决这个问题,可以采取以下步骤:

  • 在测试类上添加注解:
  • @TestInstance(PER_CLASS)@ExtendWith(MockitoExtension.class)public class KonfigurationCopyServiceTest {    @InjectMocks    private EKonfigurationCopyServiceImpl konfigurationCopyServiceImpl;    @MockBean    private FileProcessRecordServiceImpl fileProcessRecordService;    @BeforeAll    public void setUp() {        MockedStatic
    mockSpringUtil = Mockito.mockStatic(SpringUtil.class); mockSpringUtil.when(() -> SpringUtil.getActiveProfile()).thenReturn("dev"); } @BeforeEach public void init() { // 其他方法的模拟 } @Test void test1() { // 测试方法内容 } @Test void test2() { // 测试方法内容 }}

    总结

    通过以上方法,您可以轻松地在测试类中使用Mockito来模拟静态方法。记得在多个测试方法中使用静态方法时,确保在每个测试方法开始时重新初始化静态 mock,以避免上述异常。

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

    你可能感兴趣的文章
    Python 基础知识点整理与分享,期盼你的交流!
    查看>>
    python 基础第七篇
    查看>>
    Python编程:Tkinter图形界面设计(1)
    查看>>
    Python 基础语法:None
    查看>>
    Python 基础语法:基本数据类型(一)
    查看>>
    python编程读取写入excel_Python读取txt内容写入xls格式excel中的方法
    查看>>
    Python 基础语法:基本数据类型(字典)
    查看>>
    Python 基础语法:基本数据类型(字符串)
    查看>>
    Python 基础语法:基本数据类型(集合)
    查看>>
    Python编程的终极十大工具
    查看>>
    python 堆排序
    查看>>
    python编程方式之一-函数式编程
    查看>>
    python 复习计划
    查看>>
    Python 多处理 apply_async 永远不会在 Windows 7 上返回结果
    查看>>
    Python 多处理 Numpy 随机
    查看>>
    Python 多处理 >= 125 列表永远不会完成
    查看>>
    Python 多处理:在第一个子错误时中止映射
    查看>>
    Python 多处理不断产生 pythonw.exe 进程而不做任何实际工作
    查看>>
    Python 多处理从不加入
    查看>>
    Python 多处理如何优雅地退出?
    查看>>