【Junit】单元测试Mock静态方法

本地开发环境说明

开发依赖版本
Spring Boot3.0.6
JDK20

pom.xml主要依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- mock静态方法需要引入这个依赖 -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-inline</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

写一个静态方法

package com.wen3.framework.junit.utils;

public class DemoUtils {

    public static String hello(String name) {
        return String.join(",", "hello", name);
    }
}

单元测试

package com.wen3.framework.junit.statictest;

import com.wen3.framework.junit.utils.DemoUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

public class StaticTest extends Assertions {

    @Test
    void testHello() {
        // 测试没有mock的情况
        String name = RandomStringUtils.randomAlphabetic(10);
        String testResult = DemoUtils.hello(name);
        assertEquals("hello,"+name, testResult);

        // mock静态方法
        Mockito.mockStatic(DemoUtils.class);
        String valueMock = RandomStringUtils.randomAlphabetic(10);
        when(DemoUtils.hello(anyString())).thenReturn(valueMock);
        testResult = DemoUtils.hello(name);
        assertEquals(valueMock, testResult);
    }
}

报错

org.mockito.exceptions.base.MockitoException: 
The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks

Mockito's inline mock maker supports static mocks based on the Instrumentation API.
You can simply enable this mock mode, by placing the 'mockito-inline' artifact where you are currently using 'mockito-core'.
Note that Mockito's inline mock maker is not supported on Android.

如果没有引入mockito-inline这个依赖,使用mock静态方法,则会抛这个异常

单元测试运行结果

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

太空眼睛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值