What is the difference between:
verify(mock, times(1)).myMethod(Matchers.isA(String.class));
verify(mock, times(1)).myMethod(Matchers.anyString());
from the Mockito library? Both pass for my method and I'm wondering which one is "better" to use.
What is the difference between:
verify(mock, times(1)).myMethod(Matchers.isA(String.class));
verify(mock, times(1)).myMethod(Matchers.anyString());
from the Mockito library? Both pass for my method and I'm wondering which one is "better" to use.
isA
checks that the class matches the expected class. In Mockito 1.x, any
, anyObject
, and anyString
ignore the argument entirely including its type, even though any
can take a class parameter and anyString
specifies it in the name.
Typically, unless you have a reason to guard against an incompatible argument being passed in, you can probably stick with any
and anyString
. Mockito style prefers flexible test cases, which means verifying only the things that you are explicitly checking, and deliberately allowing everything else to be unspecified.
UPDATE: Mockito committer Brice has offered some historical background and future direction:
For historical reference,
any
is a shorthand alias ofanything
, at that time the API was forcing one to cast, and contributors and/or commiters thought about passing the class as a param to avoid this cast, without changing the semantic of this API. However this change eventually modified what people thought that this API was doing. This will be fixed in mockito 2+