Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito isA() & any...()

Tags:

mockito

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.

like image 789
user2759013 Avatar asked Sep 06 '25 04:09

user2759013


1 Answers

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+

like image 180
Jeff Bowman Avatar answered Sep 07 '25 23:09

Jeff Bowman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!