Mockito 2 参数匹配器

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

请参考下面的代码:java

//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):ui

when(mockedList.contains(argThat(isValid()))).thenReturn("element");spa

 

//following prints "element"rest

System.out.println(mockedList.get(999));code

 

//you can also verify using an argument matcherhtm

verify(mockedList).get(anyInt());ci

 

//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

相关文章
相关标签/搜索