我在我的应用程序中使用了Android-DDP库。这个库实现了Distributed Data Protocol
。如何使用Robolectric测试AsyncTask?
我想实施一些集成测试,其中我不想嘲笑DDP-client
。我在同一台机器上安装了后端实例,所以我不担心网络问题。
我开始用这样的测试结构:
@Inject
Meteor meteor;
@Test
public void testSendMessage() throws Exception {
final Object[] params = new Object[]{"example params"};//some params are build here.
final Result result = Result.empty(); //my class for tests;
final CountDownLatch latch = new CountDownLatch(1);
meteor.call("send_message", params, new ResultListener() {
@Override
public void onSuccess(String result) {
result.setSucess(result);
latch.countDown();
}
@Override
public void onError(String error, String reason, String details) {
result.setError(error, reason, details);
latch.countDown();
}
});
latch.await(); // here we block the main thread, and callback will not be called because of it.
//here goes some assertions, but they will never call.
}
但回调从来没有叫。经过一番小调查,我发现在引擎盖下,ddp-client
使用AsyncTask
来执行后台操作并将回调传递给客户端代码。
由于AsyncTask.onPostExecute
总是呼吁main thread
我无法摆脱回拨电话:测试块main thread
直到调用回调,但回调不会被调用,因为AsyncTask.onPostExecute
是呼吁main thread
(其被测试封锁)
所以,要解决这个问题,我需要在不同的线程中运行tests
或AsyncTask.onPostExecute
,或者不要阻塞线程来测试结果。这可能吗?
我知道的,问题的AsyncTask,但它是从第三方库。 –
我不想粗鲁,但你应该改变第三方库。但是,如果你不能,你可以从我的文章中加入的github链接中使用ShadowAsyncTask –
@MasterDisaster:你没有链接ShadowAsyncTask,你链接到了ShadowAsyncTaskTest。 –