Jim*_*eón 5 android unit-testing mockito powermock retrofit2
我想做一个单元测试验证,如果function1()还是function2()被调用.我之前没有使用过回调,你能告诉我怎么做吗?
public void sendData(HttpService service, Document userData) {
Call<String> call = service.updateDocument(getId(), userData);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
function1(response.code());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
function2();
}
});
}
Run Code Online (Sandbox Code Playgroud)
我无法尝试,但它应该有效。也许您必须修复通用类型转换错误,例如mock(Call.class);.
@Test
public void should_test_on_response(){
Call<String> onResponseCall = mock(Call.class);
doAnswer(invocation -> {
Response response = null;
invocation.getArgumentAt(0, Callback.class).onResponse(onResponseCall, response);
return null;
}).when(onResponseCall).enqueue(any(Callback.class));
sendData(....);
// verify function1
}
@Test
public void should_test_on_failure(){
Call<String> onResponseCall = mock(Call.class);
doAnswer(invocation -> {
Exception ex = new RuntimeException();
invocation.getArgumentAt(0, Callback.class).onFailure(onResponseCall, ex);
return null;
}).when(onResponseCall).enqueue(any(Callback.class));
sendData(....);
// verify function2
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
938 次 |
| 最近记录: |