Mockito 通过使用 equals() 这种自然的 Java 样式来校验参数值。有时候,当需要有其他一些灵活性的时候,你可能会要求使用参数匹配(argument matchers)。

创新互联服务项目包括工农网站建设、工农网站制作、工农网页制作以及工农网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,工农网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到工农省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!
请参考下面的代码:
//stubbing using built-in anyInt() argument matcherwhen(mockedList.get(anyInt())).thenReturn("element");//stubbing using custom matcher (let's say isValid() returns your own matcher implementation):when(mockedList.contains(argThat(isValid()))).thenReturn("element");//following prints "element"System.out.println(mockedList.get(999));//you can also verify using an argument matcherverify(mockedList).get(anyInt());//argument matchers can also be written as Java 8 Lambdasverify(mockedList).add(argThat(someString -> someString.length() > 5)); |
参数匹配运行进行灵活校验或者打标。
请访问 https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/hamcrest/MockitoHamcrest.html 链接来查看更多有关自定义参数匹配器/hamcrest matchers(custom argument matchers/hamcrest matchers)的内建参数匹配器和示例。
更多有关 自定义参数匹配器(custom argument matchers)的使用,请参考 ArgumentMatcher 类的 API 文档。
在使用复杂参数匹配器的时候需要谨慎。尝试给一个干净并且简单的测试的时候,尽量选择自然的参数匹配使用的是 equals() 对比相对偶然使用 anyX() 来说。有时候可能对你的代码进行一些重构来允许 equals() 进行匹配,或者可以实现(implement)equals()方法来帮助进行测试。
同时,请阅读 Capturing arguments for further assertions (Since 1.8.0) 页面中的内容,或者参考 ArgumentCaptor 类的 API。
ArgumentCaptor 是有关参数匹配器的是特殊实现,能够为后面的对比(assertions)捕获参数变量。
如果你现在正在使用参数匹配器,所有参数(all arguments)都必须由 matches 提供。
下面的示例代码显示校验,但是一些将会应用到打标中。
verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));//above is correct - eq() is also an argument matcherverify(mock).someMethod(anyInt(), anyString(), "third argument");//above is incorrect - exception will be thrown because third argument is given without an argument matcher. |
像 anyObject(), eq() Matcher 方法不会返回 matchers。
在内部,他们将会在堆栈(stack)中记录一个 matcher 然后返回一个虚假的值(通常为 null)。
这种实现方式是基于 Java 编译器中有关静态类型的安全性问题而考虑的,从而带来的结果是你不能在 verified/stubbed 方法外部使用 anyObject(), eq()。
https://www.cwiki.us/display/MockitoZH/Argument+matchers