争论的Mockito匹配器(如any
,argThat
,eq
,same
,和ArgumentCaptor.capture()
)表现非常不同,从Hamcrest匹配器.
Mockito匹配器经常导致InvalidUseOfMatchersException,即使在使用任何匹配器后执行很长时间的代码中也是如此.
Mockito匹配器受到奇怪的规则的影响,例如,如果给定方法中的一个参数使用匹配器,则只需要对所有参数使用Mockito匹配器.
当覆盖Answer
s或使用(Integer) any()
等时,Mockito匹配器可能会导致NullPointerException .
使用Mockito匹配器以某种方式重构代码可能会产生异常和意外行为,并且可能完全失败.
为什么Mockito匹配器是这样设计的,它们是如何实现的?
我正在尝试为通话创建一个模拟器.说我有这个方法我试图存根:
class ClassA {
public String getString(String a) {
return a + "hey";
}
}
Run Code Online (Sandbox Code Playgroud)
我想嘲笑的是:第一个例子是
when(classA.getString(eq("a")).thenReturn(...);`
Run Code Online (Sandbox Code Playgroud)
在同一测试案例中
when(classA.getString([anything that is not a])).thenReturn(somethingelse);
Run Code Online (Sandbox Code Playgroud)
第二个案例是我的问题:我如何匹配anyString()
"a"以外的其他?
我创建了一个ArgumentMatcher
,
private class IsListOf2Elements implements ArgumentMatcher<List<String>>{
@Override
public boolean matches(List<String> argument) {
return ((List<String>)argument).size()==2;
}
}
Run Code Online (Sandbox Code Playgroud)
我想否定这个匹配,所以当大小不是 2 时匹配,
Mockito.doReturn(false).when(mock).addAll(Mockito.argThat(AdditionalMatchers.not(new IsListOf2Elements())));
Run Code Online (Sandbox Code Playgroud)
但这是不正确的。我明白了,
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
No matchers found for additional matcher Not(?)
-> at my.test.own.Mockito_aTest.test4e(Mockito_aTest.java:136)
Run Code Online (Sandbox Code Playgroud)