[英]How to test AsyncTask using Robolectric?
I use Android-DDP library in my application. 我在我的应用程序中使用Android-DDP库。 This library implements the Distributed Data Protocol
. 该库实现了Distributed Data Protocol
。
I would like to implement some integration tests, in which I don't want to mock the DDP-client
. 我想实现一些集成测试,其中我不想模拟DDP-client
。 I've setup the backend instance on the same machine, so I don't worry about network issues. 我在同一台机器上设置了后端实例,所以我不担心网络问题。
I started with such test structure: 我开始使用这样的测试结构:
@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.
}
But the callback was never called. 但回调从未被调用过。 After a small investigation, I've found that under the hood, ddp-client
uses AsyncTask
to perform background operation and to deliver callbacks to the client code. 经过一个小小的调查后,我发现ddp-client
使用AsyncTask
来执行后台操作并将回调传递给客户端代码。
Since AsyncTask.onPostExecute
is always called on the main thread
I am not able to get call from callback: Tests blocks the main thread
until the callback is called, but callback is never called because AsyncTask.onPostExecute
is called on the main thread
(which is blocked by tests) 由于总是在main thread
上调用AsyncTask.onPostExecute
我无法从回调中调用: 测试阻塞main thread
直到调用回调,但是从不调用回调,因为在main thread
上调用了AsyncTask.onPostExecute
(这是被测试阻止)
So, to solve the problem I need to run tests
or AsyncTask.onPostExecute
in different threads, or somehow not to block the thread to test the result. 所以,要解决这个问题,我需要在不同的线程中运行tests
或AsyncTask.onPostExecute
,或者不管怎样都不阻止线程来测试结果。 Is that possible to do? 这可能吗?
First: Don't use AsyncTask 第一:不要使用AsyncTask
Second: Just see this: https://github.com/robolectric/robolectric/blob/8b9af4c1f5dec90c07d2532587df48188e9f2c68/shadows/framework/src/main/java/org/robolectric/shadows/ShadowAsyncTask.java 第二:看看这个: https : //github.com/robolectric/robolectric/blob/8b9af4c1f5dec90c07d2532587df48188e9f2c68/shadows/framework/src/main/java/org/robolectric/shadows/ShadowAsyncTask.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.