簡體   English   中英

如何使用Robolectric測試AsyncTask?

[英]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 (這是被測試阻止)

所以,要解決這個問題,我需要在不同的線程中運行testsAsyncTask.onPostExecute ,或者不管怎樣都不阻止線程來測試結果。 這可能嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM