我是单元测试新手,尝试使用 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.
您使用哪个版本的 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"));
}
}