mock静态方法指引
发布日期:2025-04-14 11:09:16 浏览次数:8 分类:精选文章

本文共 2169 字,大约阅读时间需要 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,以避免上述异常。

    上一篇:Modbus Poll/Slave 模拟器使用教程
    下一篇:mock的使用二(根据数据模板生成模拟数据)

    发表评论

    最新留言

    做的很好,不错不错
    [***.243.131.199]2025年05月18日 11时57分46秒