I am creating a custom argument matcher in mockito. Using this example:
class IsListOfTwoElements extends ArgumentMatcher<List> {
public boolean matches(Object list) {
return ((List) list).size() == 2;
}
}
This made me wonder why the type of the parameter list is Object instead of List.
Can the argument passed to the match function be something else? And if so shouldn’t the example check the type of the parameter and return false if it isn’t a List?
To rephrase the question a little:
Does mockito promise to only pas the correct type to the matches function? If so, why doesn’t it use the generic type. And if not why doesn’t the example return false if the wrong type is passed to it?
Because the mockito matchers use Hamcrest matchers, in the javadoc link you provided, you’ll see that it inherits the signature of
matchesin interfaceorg.hamcrest.Matcherwhich appear to not be generic in the actual interface.If the compiler has made his job correctly you can assume you’ll get the correct type though.
Note that the
ArgumentCaptorapproach is now recommanded for complex assertions, where you can use AssertJ (maintained clone of FEST-Assert) for example.