Issue
I'm trying to implement this JUnit code:
private BinlistsService binlistsService = Mockito.mock(BinlistsService.class);
@Mock
Optional<BinLists> binList = null;
@BeforeEach
public void beforeEachTest() throws IOException {
BinLists binLists = new BinLists();
binLists.setId(1);
....
binList = Optional.of(binLists);
}
@Test
public void testBinCountryCheckFilterImpl() {
when(binlistsService.findByName(anyString())).thenReturn(binList);
}
But I get this error stack:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.util.Optional
Mockito cannot mock/spy because :
- final class
at org.data
Do you know how I can fix this issue?
Solution
Remove @Mock
on the Optional<BinLists>
field.
Optional
is a simple class that can be easily created and controlled by you, so you do not need to mock it .Just create an actual instance when you need it which you already do it in beforeEachTest()
:
private BinlistsService binlistsService = Mockito.mock(BinlistsService.class);
Optional<BinLists> binList = null;
@BeforeEach
public void beforeEachTest() throws IOException {
BinLists binLists = new BinLists();
binLists.setId(1);
....
binList = Optional.of(binLists);
}
@Test
public void testBinCountryCheckFilterImpl() {
when(binlistsService.findByName(anyString())).thenReturn(binList);
}
Answered By - Ken Chan