I'm new to Unit testing and Tried to Mock a map using Mockito.
When I tried to mock ConcurrentHashMap it throws error like this . Not only Hash map it throws error for all Object .
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
Tried With List and Sets as well getting same error . I tried with JDK 19 getting same error.
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.
Which version of Mockito do you use?
I create an example in this GitHub repository and mocking ConcurrentHashMap
seems to work fine.
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"));
}
}