Java 單元測試的時候若是在一個mock內 使用多個 ArgumentMatchers ,根據不一樣參數返回不通結果,按照下面的寫法:java
T mock = Mock(T.class);
when(mock.method(argThat(new ArgumentMatcher<Object>() {
@Override
public boolean matches(Object arg0) {
//比較邏輯1
}
}))).thenReturn(result1);
when(mock.method(argThat(new ArgumentMatcher<Object>() {
@Override
public boolean matches(Object arg0) {
//比較邏輯2
}
}))).thenReturn(result2);
when(mock.method(argThat(new ArgumentMatcher<Object>() {
@Override
public boolean matches(Object arg0) {
//比較邏輯3
}
}))).thenReturn(result3);
複製代碼
實際執行單元測試的時候會報java.lang.NullPointerExceptionbash
解決辦法:ide
doReturn(result1).when(mock).method(
argThat(new ArgumentMatcher<Object>() {
@Override
public boolean matches(Object argument) {
///比較邏1
}
}));
doReturn(result2).when(mock).method(
argThat(new ArgumentMatcher<Object>() {
@Override
public boolean matches(Object argument) {
///比較邏2
}
}));
doReturn(result1).when(mock).method(
argThat(new ArgumentMatcher<Object>() {
@Override
public boolean matches(Object argument) {
///比較邏3
}
}));
複製代碼
便可正常執行。單元測試