无法模拟 Mockito 中的任何内容

问题描述 投票:0回答:1

我是单元测试新手,尝试使用 Mockito 模拟地图。

当我尝试模拟 ConcurrentHashMap 时,它会抛出这样的错误。不仅是哈希映射,它还会为所有对象抛出错误。

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.concurrent.ConcurrentHashMap;

import static org.mockito.Mockito.mock;

class UtilsTest {


    @BeforeEach
    void setUp() {
        ConcurrentHashMap mockedMap = mock(ConcurrentHashMap.class);
    }

    @Test
    void lessLoadedServersCount(){

    }
}
org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class java.util.concurrent.ConcurrentHashMap.

Mockito can only non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.


Java               : 11
JVM vendor name    : OpenLogic
JVM vendor version : 11.0.19+7-adhoc.admin.jdk11u
JVM name           : OpenJDK 64-Bit Server VM
JVM version        : 11.0.19+7-adhoc.admin.jdk11u
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 13.2.1



Underlying exception : java.lang.UnsupportedOperationException: Cannot define class using reflection: Could not find sun.misc.Unsafe

尝试使用列表和集合也得到相同的错误。我尝试使用 JDK 19 得到同样的错误。

org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class java.util.ArrayList.

Mockito can only non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class java.util.HashSet.

Mockito can only non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
java unit-testing mockito junit5
1个回答
0
投票

您使用哪个版本的 Mockito?

我在这个 GitHub 存储库中创建了一个示例,并且模拟

ConcurrentHashMap
似乎工作正常。

class UtilTest {

    private ConcurrentHashMap map;

    @BeforeEach
    void setUp() {
        map = mock(ConcurrentHashMap.class);
    }

    @Test
    void test(){
        when(map.get("key")).thenReturn("value");

        assertEquals("value", map.get("key"));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.