如何防止一个方法在测试中调用另一个方法?
How to prevent a method from calling another method in test?
public void makeLoginRequest(){
view.log(sessionHandler.getEncodedCredentials());
Call loginCall = apiService.getLoginInfo("application/json", "application/json"
, "SPT", "Android", sessionHandler.getEncodedCredentials());
loginCall.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
handleLoginResponse(response);
}
@Override
public void onFailure(Call<User> call, Throwable t) {
handleLoginFailure(t);
}
});
}
我正在尝试使用 JUnit 和 Mockito 测试此方法。此方法属于演示者 class。为了测试这个我 运行
presenter.makeLoginRequest();
那么当 onResponse 被调用时
我使用从未被调用的 verify(presenter).handleLoginResponse(response);
。问题是它将继续 运行 handleLoginResponse(response);
中的所有内容。我不想在这个方法中执行什么,而只需要验证是否调用了这个方法。
我怎样才能忽略方法执行,或者测试它的最佳方法是什么?
有两种方法可以做到这一点:
- 让你的演讲者成为一个
mock
对象
presenter = mock<Presenter>()
- 将此添加到您的测试中
doNothing().when(presenter).handleLoginResponse(any());
public void makeLoginRequest(){
view.log(sessionHandler.getEncodedCredentials());
Call loginCall = apiService.getLoginInfo("application/json", "application/json"
, "SPT", "Android", sessionHandler.getEncodedCredentials());
loginCall.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
handleLoginResponse(response);
}
@Override
public void onFailure(Call<User> call, Throwable t) {
handleLoginFailure(t);
}
});
}
我正在尝试使用 JUnit 和 Mockito 测试此方法。此方法属于演示者 class。为了测试这个我 运行
presenter.makeLoginRequest();
那么当 onResponse 被调用时
我使用从未被调用的 verify(presenter).handleLoginResponse(response);
。问题是它将继续 运行 handleLoginResponse(response);
中的所有内容。我不想在这个方法中执行什么,而只需要验证是否调用了这个方法。
我怎样才能忽略方法执行,或者测试它的最佳方法是什么?
有两种方法可以做到这一点:
- 让你的演讲者成为一个
mock
对象
presenter = mock<Presenter>()
- 将此添加到您的测试中
doNothing().when(presenter).handleLoginResponse(any());