问题描述
我创建了一个ArgumentMatcher
private class IsListOf2Elements implements ArgumentMatcher<List<String>>{
@Override
public boolean matches(List<String> argument) {
return ((List<String>)argument).size()==2;
}
}
我要取消此匹配,因此当大小不为2时匹配
I want to negate this match, so match when size is not 2,
Mockito.doReturn(false).when(mock).addAll(Mockito.argThat(AdditionalMatchers.not(new IsListOf2Elements())));
但这是不正确的.我明白了,
But this is not correct. I get,
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
No matchers found for additional matcher Not(?)
-> at my.test.own.Mockito_aTest.test4e(Mockito_aTest.java:136)
推荐答案
作为参考,请注意 Hamcrest匹配器和Mockito匹配器的行为非常. Hamcrest的无状态Matcher对象将match函数表示为实例,可以包装它们以反转其结果. Mockito的注册匹配者"仅通过副作用起作用.
For reference, be aware that Hamcrest matchers and Mockito matchers behave very differently. Hamcrest's stateless Matcher objects represent the match function as an instance, and can be wrapped to invert their results; Mockito's "registered matchers" work only via side-effects.
argThat
将Hamcrest匹配器改成Mockito匹配器,Hamcrest的CoreMatchers.not
反转Hamcrest匹配器,而Mockito的AdditionalMatchers.not
反转Mockito匹配器(通过副作用).这是CoreMatchers.not
总是返回Matcher<T>
而AddionalMatchers.not
返回任意T
的部分原因;它在看不见的Mockito状态下运行.
argThat
adapts a Hamcrest matcher into a Mockito matcher, Hamcrest's CoreMatchers.not
inverts a Hamcrest matcher, and Mockito's AdditionalMatchers.not
inverts a Mockito matcher (via side-effects). This is part of the reason that CoreMatchers.not
always returns a Matcher<T>
, while AddionalMatchers.not
returns an arbitrary T
; it's operating on Mockito state you can't see.
这会给您以下行为:
// BAD: Don't use AdditionalMatchers to invert a Hamcrest matcher.
doReturn(false).when(mock).addAll(
Mockito.argThat(AdditionalMatchers.not(new IsListOf2Elements())));
// GOOD: Use AdditionalMatchers to invert a Mockito matcher. (See ericj's answer.)
doReturn(false).when(mock).addAll(
AdditionalMatchers.not(Mockito.argThat(new IsListOf2Elements())));
// ALSO GOOD: Use CoreMatchers to invert a Hamcrest matcher. (See troig's answer.)
doReturn(false).when(mock).addAll(
Mockito.argThat(CoreMatchers.not(new IsListOf2Elements())));
如果您要进行的异常行为涉及异常行为,则还可以使用更具体的覆盖进行异常行为除了特定的例外情况外,还具有一般行为.
If the exception you're making is about stubbed behavior, you can also use a more-specific override to stub the general behavior in addition to the specific exception.
这篇关于如何在Mockito中取消ArgumentMatcher?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!