Explain Codes LogoExplain Codes Logo

Can Mockito stub a method without regard to the argument?

java
mockito
testing
argument-matchers
Nikita BarsukovbyNikita Barsukov·Oct 4, 2024
TLDR

To stub any method call in Mockito without concerning about the arguments, you can use any():

when(mockObject.method(any())).thenReturn("Fixed Response");

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() or notNull() 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() and hashCode() 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() or any() — 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:

when(mock.someMethod(anyString())).thenAnswer(invocation -> { String arg = invocation.getArgument(0); // The method says, "I'll be back" based on the argument return arg + " is back."; });