Mockito isA() & any…()

早过忘川 提交于 2020-01-12 11:53:51

问题


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.


回答1:


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+



来源:https://stackoverflow.com/questions/21430378/mockito-isa-any

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!