Java 如何使用Robolectric测试异步任务?

Java 如何使用Robolectric测试异步任务?,java,android,unit-testing,android-asynctask,robolectric,Java,Android,Unit Testing,Android Asynctask,Robolectric,我在应用程序中使用库。此库实现分布式数据协议 我想实现一些集成测试,在这些测试中我不想模拟DDP客户机。我已经在同一台机器上设置了后端实例,所以我不担心网络问题 我从这样的测试结构开始: @Inject Meteor meteor; @Test public void testSendMessage() throws Exception { final Object[] params = new Object[]{"example params"};//some params are

我在应用程序中使用库。此库实现分布式数据协议

我想实现一些集成测试,在这些测试中我不想模拟
DDP客户机
。我已经在同一台机器上设置了后端实例,所以我不担心网络问题

我从这样的测试结构开始:

@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客户端
使用
AsyncTask
执行后台操作并向客户端代码发送回调

由于总是在
主线程上调用
,因此我无法从回调中获取调用:测试将阻止
主线程
,直到调用回调为止,但是从不调用回调,因为在
主线程上调用了
AsyncTask.onPostExecute
(被测试阻止)


因此,为了解决这个问题,我需要在不同的线程中运行
测试
异步任务.onPostExecute
,或者以某种方式不阻塞线程来测试结果。这可能吗?

首先:不要使用AsyncTask


第二:看看这个:

我知道,关于AsyncTask问题,但它来自第三方库。我不想粗鲁,但你应该更改第三方库。但如果你不能,你可以从github链接使用ShadowAsyncTask,我在我的post@MasterDisaster:您未链接ShadowAsyncTask,但已链接到ShadowAsyncTaskTest。