Mockito 2 参数匹配器

时间:2019-09-21
本文章向大家介绍Mockito 2 参数匹配器,主要包括Mockito 2 参数匹配器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

请参考下面的代码:

//stubbing using built-in anyInt() argument matcher
when(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 matcher
verify(mockedList).get(anyInt());
 
//argument matchers can also be written as Java 8 Lambdas
verify(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 matcher
 
verify(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

原文地址:https://www.cnblogs.com/huyuchengus/p/11561944.html