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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HoneyMoose

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值