Image AI-generated on Shutterstock

Taming a Silly Generic Warning

Unlocking Mockito’s mock() Method

Kenneth Kousen
4 min readJun 22, 2023

--

https://pragprog.com/newsletter/

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 addor 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 Listand then shows method calls on it, which should be happening only inside whatever class they’re actually…

--

--

Kenneth Kousen
The Pragmatic Programmers

Author of the books Mockito Made Clear, Help Your Boss Help You, Kotlin Cookbook, Modern Java Recipes, Gradle Recipes for Android, and Making Java Groovy