Java 單元測試的時候如果在一個mock內 使用多個 ArgumentMatchers ,根據不同引數返回不通結果,按照下面的寫法:
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.NullPointerException
解決辦法:
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
}
}));
複製程式碼
即可正常執行。