Taming a Silly Generic Warning
Unlocking Mockito’s mock() Method
This warning is such a small, unimportant thing, but it’s bugged me for a long time — and now I’ve fixed it. In the unlikely case it affects you as well, let me show you how to deal with the problem.
The first (the very first) example in the Mockito documentation is:
//Let's import Mockito statically so that the code looks clearer
import static org.mockito.Mockito.*;
//mock creation
List mockedList = mock(List.class);
//using mock object
mockedList.add("one");
mockedList.clear();
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
To be honest, this isn’t a great example. First, as they point out in the docs, you shouldn’t mock a List
. They’re only doing it because every Java developer is familiar with lists, so they already understand the calls to add
or clear
.
Second, don’t test your mocks. You mock a dependency, inject that dependency into the class you’re testing, and call methods on the test class. This example mocks a List
and then shows method calls on it, which should be happening only inside whatever class they’re actually…