我想为单个方法使用两个自定义匹配器。基本上,如果我传递方法VALUE_A,我希望它返回RESULT_A,并且如果我将它传递给VALUE_B,我希望它返回RESULT_B。所以这里有一个代码摘录:当我将多个自定义匹配器分配给单个方法时,Mockito会出现奇怪的现象
class IsNonEmpty extends ArgumentMatcher<Get> {
public boolean matches(Object get) {
//For some reason, this method is called when I assign the IsEmpty matcher to MockHtable.get()
//When this happens, the value of the get argument is null, so this method throws an NPE
return Arrays.equals(((Get) get).getRow(), SERIALIZATION_HELPER.getValidBytes(key));
}
}
class IsEmpty extends ArgumentMatcher<Get> {
public boolean matches(Object get) {
return !(Arrays.equals(((Get) get).getRow(), SERIALIZATION_HELPER.getValidBytes(key)));
}
}
[...]
//This line executes just fine
Mockito.when(mockHTable.get(Mockito.argThat(new IsNonEmpty()))).thenReturn(dbResult);
[...]
//This line calls IsNonEmpty.matches() for some reason. IsNonEmpty.matches() throws an NPE
Mockito.when(mockHTable.get(Mockito.argThat(new IsEmpty()))).thenReturn(emptyResult);
当我指定的IsEmpty定制匹配到mockHTable.get()方法中,它调用IsNonEmpty.matches()函数。不知道为什么这样做。所以我把IsNonEmpty类更改为:
class IsNonEmpty extends ArgumentMatcher<Get> {
public boolean matches(Object get) {
//For some reason, this method is called when I assign the IsEmpty matcher. Weird, no?
if(get == null) {
return false;
}
return Arrays.equals(((Get) get).getRow(), SERIALIZATION_HELPER.getValidBytes(key));
}
}
然后一切正常!当我将IsEmpty匹配器分配给mockHTable.get()函数时,IsNonEmpty.matches()仍然被调用,但是我的匹配器完全按照他们的方式工作。
那么有什么交易?为什么会发生?我的工作是否是补偿这种古怪行为的适当方法,还是我做错了?