2017-04-18 42 views
1

我在我的應用程序中使用了Android-DDP庫。這個庫實現了Distributed Data Protocol如何使用Robolectric測試AsyncTask?

我想實施一些集成測試,其中我不想嘲笑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直到調用回調,但回調不會被調用,因爲AsyncTask.onPostExecute是呼籲main thread(其被測試封鎖)

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

回答

0
+0

我知道的,問題的AsyncTask,但它是從第三方庫。 –

+0

我不想粗魯,但你應該改變第三方庫。但是,如果你不能,你可以從我的文章中加入的github鏈接中使用ShadowAsyncTask –

+0

@MasterDisaster:你沒有鏈接ShadowAsyncTask,你鏈接到了ShadowAsyncTaskTest。 –