Can Mockito stub a method without regard to the argument?
⚡TLDR
To stub any method call in Mockito without concerning about the arguments, you can use any()
:
Simply replace method
with the method you're going to mock, and "Fixed Response"
with the object you want the mocked method to return. This approach works with any argument type.
To ensure effective testing, consider:
- IMDb your mocks with
any()
ornotNull()
when argument specifics aren't worth the Oscars. - Adopt
ArgumentMatchers.*
for a red-carpet welcome to your matchers from Mockito version 2.1.0 onwards. - Invite
equals()
andhashCode()
to make your objects glitter in the crowd of argument matching. - Introduce the
Answer
object for those blockbuster stubbing scenarios where the lead actor is 'complexity'.
Deep Dive into Matchers
Argument matchers provide a powerful way to simulate conditions for your tests.
The basics
anyObject()
orany()
— These matchers don't care about the type or value of the parameter. When a method doesn't affect a parameter — use this match.eq()
— When a parameter's specific value needs to match. Helps when a method affects the parameter.any(Class<T> type)
— Useful when different types float around overloaded methods.
Legacy testing
Maintaining legacy code can feel like gardening a forest but the rules below help in ensuring it isn't a jungle out there:
- Replace the trees with bonsai mocks. Isolate the test units.
- Stub to simulate complex scenarios without changing the real code.
- Use Mockito argument matchers to avoid catching unintended methods in your snare.
Tricks under the cape
Here are some skills for a better casting call:
doReturn().when()
to handle void methods or the ones with side effects.doAnswer(new Answer(...))
for scripts requiring improvisation based on the arguments thrown.
Answer objects: the stunt doubles
Answer objects—the stand-ins for the main actors when the stub needs to react to arguments:
Linked
Linked
Was this article helpful?