I try to mock a List-Collection with Mockito along jUnit5.
I try to mock the following collection:
@Test
public void testMock() {
List<Integer> listMock = mock(List.class);
}
I get a warning in Eclipse: "Type safety: The expression of type List needs unchecked conversion to conform to List ".
I tried to fix it, but I'm not sure if there is a structural problem with the mocking with the software framework? Is there a way to fix this warning at all or do I have to accept an unchecked conversion, when I do a mocking of collections?
I'm thankful for any clues.
You can get around that problem of mocking parameterized types by using Mockito's @Mock
annotation, e.g. like this:
class MyTests {
@Mock
List<String> listOfStrings;
@BeforeEach
void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testMock() {
listOfStrings.add("a String");
}
}
If you are using Mockito's Jupiter Extension you can even get rid of the initMocks()
method.
That said, mocking a List
usually makes not a lot of sense but I guess you've chosen this just as an example for any parameterized type.