[Junit] Unit test Mock static method

Description of local development environment

development dependencies Version
Spring Boot 3.0.6
JDK 20

pom.xml mainly depends on

<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>

write a static method

package com.wen3.framework.junit.utils;

public class DemoUtils {
    
    

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

unit test

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);
    }
}

report error

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.

If this dependency is not introduced mockito-inlineand the mock static method is used, this exception will be thrown

Unit test run results

insert image description here

Guess you like

Origin blog.csdn.net/friendlytkyj/article/details/131021768