Explain Codes LogoExplain Codes Logo

Mockito match any class argument

java
mockito
unit-testing
test-driven-development
Anton ShumikhinbyAnton Shumikhin·Dec 4, 2024
TLDR

Make use of any() to match any type of arguments or any(Class<T>) for a specific type T.

An example would be:

when(mock.someMethod(any())).thenReturn(someValue);

Or for a specific class:

when(mock.function(any(MyClass.class))).thenReturn(someValue);

Here someMethod and someValue should be replaced with your method's name and the expected return value, respectively. MyClass.class should correspond to the class type you're testing.

Mockito Matchers: Picking the Right Tool for The Job

Even when coding, it's crucial to use the right tool for the job. In Mockito, those tools are matchers. They help specify conditions for stubbing. any() and any(Class<T>) are just the tip of the iceberg, like butter knives in a full chef's knife set.

Ready-Made Matchers

In addition to any(), Mockito offers isA(Class<T>) and (T) notNull() matchers.

when(mock.someMethod(isA(MyClass.class))).thenReturn(someValue); // This method won't run if it's on a diet. It doesn't like "null" calories. when(mock.someMethod(notNull())).thenReturn(someValue);

Craft Your Own Matchers

When the pre-made options don't cut it, consider going bespoke. A MyCustomMatcher class could extend ArgumentMatcher and validate subclasses.

when(mock.someMethod(argThat(new MyCustomMatcher()))).thenReturn(someValue);

Advanced Matchers for the Discerning Developer

Sometimes, high-level control is required in your mocks. This is where custom matchers come into play. By extending org.hamcrest.BaseMatcher, you can define highly specific conditions.

The Chameleon: Matchers.any

The Matchers.any() is a versatile matcher that adapts to any class or subclass.

when(mock.someMethod(Matchers.<Class<A>>any())).thenReturn(instanceOfB); // Returns instanceOfB: "No matter who comes knocking, B is always home."

Modelling Complex Argument Matching

For added precision with generic types or complex method signatures, a custom ArgumentMatcher works well.

when(mock.someMethod(argThat(new MyTypeSafeMatcher<>()))).thenReturn(someValue); // Safe as a type vault. Handle generics with care!

This MyTypeSafeMatcher checks the properties of the generic type to ensure the method stubbing remains accurate and easy to follow.