Photo by Abby Boggier on Unsplash

Gotta Mock ’Em All!

Or, Why Does Mockito’s ArgumentMatchers Class Need an eq Method?

The Pragmatic Programmers
5 min readJun 5, 2023

--

The Mockito testing framework lets you test classes by creating mock objects for their dependencies. Then you set the expectations on those objects by specifying exactly what their methods should return when invoked.

The eq()method is one of the ArgumentMatchers, which is a class that lets you specify more generally what the input arguments should be. It’s different from the others though. To see why, take a look at a sample of the other methods in the ArgumentMatchers class:

  • anyInt, anyDouble, and similar ones for the rest of the primitives.
  • anyString, startsWith, endsWith, contains, and other methods for strings.
  • isNull and isNotNull, which are pretty self-explanatory.

But there’s also a method called eq, which takes a single argument.

The eq methods in the ArgumentMatchers class

There are overloads for each primitive type (eq(int), eq(double), and so on) and one for any generic type (eq(T)). The question is, why do we need all those eq methods? If you know the value, why not just specify it be done with it?

--

--

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