28

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.

djm.im
  • 3,295
  • 4
  • 30
  • 45
user2759013
  • 491
  • 1
  • 10
  • 18

1 Answers1

24

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 of anything, 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+

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • Then, for the latest version at least, we should use `any()` instead of `isA()`? Is that true? – Jack Nov 16 '21 at 05:59
  • @Robert I would avoid using `any(Clazz.class)` or `anyString()` etc due to the ambiguity. If you truly don't care about the value, use `any()`, and if you need it to be a certain type use `isA(Clazz.class)`. (If you're still compiling with Java 7, you may need to be pragmatic, but should probably upgrade instead.) – Jeff Bowman Nov 16 '21 at 06:04
  • Thanks a lot, perfect explanations. But as far as I see, generally I do not need to check the value and maybe we could generally prefer using any(). – Jack Nov 16 '21 at 08:22
  • On the other hand, sometimes I use a created variable of `Clazz` e.g. `clazz`, in this case can we say that I can also pass this `clazz` instead of `any(Clazz.class)` ? – Jack Nov 16 '21 at 08:23
  • @Robert Yes, Mockito style is to check as little as possible for maximum test flexibility, so in that sense `any()` is preferred. That said, `isA` is reasonable, and easily accepts any instance of type Class including your `clazz` variable, though depending on your specific example you may have to cast the value or strip the generics for Java to accept your `isA(clazz)` parameter. – Jeff Bowman Nov 16 '21 at 10:44