当前位置:   article > 正文

【Junit】单元测试Mock静态方法_org.mockito.exceptions.base.mockitoexception: the

org.mockito.exceptions.base.mockitoexception: the used mockmaker subclassbyt

本地开发环境说明

开发依赖版本
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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

写一个静态方法

package com.wen3.framework.junit.utils;

public class DemoUtils {

    public static String hello(String name) {
        return String.join(",", "hello", name);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

单元测试

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);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

报错

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.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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

单元测试运行结果

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/280699
推荐阅读
相关标签
  

闽ICP备14008679号