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

本地开发环境说明

开发依赖 版本
Spring Boot 3.0.6
JDK 20

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静态方法,则会抛这个异常

单元测试运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/friendlytkyj/article/details/131021768