Mockito match any class argument
Make use of any()
to match any type of arguments or any(Class<T>)
for a specific type T
.
An example would be:
Or for a specific class:
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.
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.
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.
Modelling Complex Argument Matching
For added precision with generic types or complex method signatures, a custom ArgumentMatcher works well.
This MyTypeSafeMatcher
checks the properties of the generic type to ensure the method stubbing remains accurate and easy to follow.
Was this article helpful?