【发布时间】:2017-06-23 05:09:34
【问题描述】:
我正在使用 Mockito 测试我的视图,但我的测试失败了,因为应该在改造调用完成后调用一个方法。在完成改造调用后,如何模拟演示者调用谁的方法的视图?我想验证下面的unBlockUI() 是否已被调用。我的测试显示blockUI() 被调用,但unblockUI() 未被调用。
我收到一条失败消息
Wanted but not invoked:
view.unBlockUI();
在我的演示者中,我有方法
public void fetchResults(){
view.blockUI();
ResultsDataService resultsDataService = new ResultsDataService()
resultsDataService.getAllResults(new Callback<Catalog>() {
@Override
public void onResponse(Call<Catalog> call, Response<Catalog> response) {
view.unBlockUI();
}
@Override
public void onFailure(Call<Catalog> call, Throwable t) {
view.unBlockUI();
t.printStackTrace();
}
})
}
结果数据服务。
public class ResultsDataService {
private final RestApi restApi;
public CatalogDataService() {
//here I have a class that builds the REST Service
restApi = RestServiceBuilder.createService(RestApi.class);
}
public void getAllResults() {
Call<Catalog> call = restApi.getAllResults();
call.enqueue(callback);
}
}
我的测试方法
@Test
public void shouldFetchAllResults_allOK() {
presenter.fetchResults();`
verify(view).blockUI();//This is called
verify(view).unBlockUI();//this is not called
}
【问题讨论】:
-
你调用改造函数的方式将在后台执行,所以在你得到服务器的响应之前,解决方案是调用 call.execute() 应该在 asynctask 中,我想您正在使用 call.enqueue 调用 api
-
但是我不想在主线程上执行调用
-
Android 不允许在主线程上进行任何网络操作,因此,如果您想在一些网络操作之后调用任何东西,而不是并行执行,请使用 asyncTask 类。将您的 retrofit.enqueue() 替换为 retrofit.execute()。现在在你的 asynctask 的 doInBackground() 和 onPostExecute、updateUI 中调用这个 retrofit.execute() 或调用任何你想在响应后调用的东西
标签: android mockito retrofit2 powermockito