博客
关于我
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/

    你可能感兴趣的文章
    python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
    查看>>
    Python: AES加密与解密
    查看>>
    Python: Range() 最大尺寸;动态的还是静态的?
    查看>>
    Python: Windows下用 multiprocessing 的深坑
    查看>>
    python:Could not find platform independent libraries <prefix>解决方法
    查看>>
    Python:datetime tzinfo 时区名称文档
    查看>>
    Python:deepcopy(list) vs new_list = old_list[:]
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
    查看>>
    Python:TypeError:无法连接“str“和“int“对象
    查看>>
    Python:XPath 在 ElementTree 中不可用
    查看>>
    Python:从 FTP 服务器下载文件
    查看>>
    python:从列表中创建元组列表
    查看>>
    Python:从嵌套列表中删除重复项
    查看>>
    Python:从间隔映射到值
    查看>>
    Python:使用 shell=False 的子进程调用不起作用
    查看>>
    Python:修改 PATH 环境变量的平台无关方式
    查看>>
    Python:假与 0
    查看>>
    Python:函数使用
    查看>>