【问题标题】:How to test AsyncTask using Robolectric?如何使用 Robolectric 测试 AsyncTask?
【发布时间】:2017-04-18 18:49:14
【问题描述】:

我在我的应用程序中使用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 执行后台操作并将回调传递给客户端代码。

因为 AsyncTask.onPostExecute 总是在 main thread 上被调用,所以我无法从回调中获得调用:测试会阻止 main thread,直到回调被调用,但从未调用回调,因为在 main thread 上调用了 AsyncTask.onPostExecute(被测试阻止)

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

【问题讨论】:

    标签: java android unit-testing android-asynctask robolectric


    【解决方案1】:

    【讨论】:

    • 我知道,关于 AsyncTask 问题,但它来自第三方库。
    • 我不想粗鲁,但你应该改变第三方库。但如果你不能,你可以使用我在帖子中添加的 github 链接中的 ShadowAsyncTask
    • @MasterDisaster:你没有链接 ShadowAsyncTask,你链接到 ShadowAsyncTaskTest。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多