[英]How to test AsyncTask using Robolectric?
我在我的应用程序中使用Android-DDP库。 该库实现了Distributed Data Protocol
。
我想实现一些集成测试,其中我不想模拟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
来执行后台操作并将回调传递给客户端代码。
由于总是在main thread
上调用AsyncTask.onPostExecute
我无法从回调中调用: 测试阻塞main thread
直到调用回调,但是从不调用回调,因为在main thread
上调用了AsyncTask.onPostExecute
(这是被测试阻止)
所以,要解决这个问题,我需要在不同的线程中运行tests
或AsyncTask.onPostExecute
,或者不管怎样都不阻止线程来测试结果。 这可能吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.