我想为一个方法使用两个自定义匹配器。基本上,如果我通过方法 VALUE_A,我希望它返回 RESULT_A,如果我通过它 VALUE_B,我希望它返回 RESULT_B。所以这里有一段代码摘录:
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(),但我的匹配器完全按照它们应该的方式工作。
那么有什么关系呢?为什么会这样?我的变通办法是弥补这种古怪行为的充分方法,还是我做错了?