Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing async tasks with robolectric

Do you know how to implement unit testing for AsyncTasks using Robolectric ? Any pointers will be appreciated.

like image 204
bianca Avatar asked Feb 23 '13 01:02

bianca


2 Answers

Call execute(...) on the task, then to wait for the result call Robolectric.runBackgroundTasks()/Robolectric.flushBackgroundThreadScheduler() then you can assert.

@Test public void test() {     //create task     MyAsyncTask asyncTask = new MyAsyncTask();      //start task     asyncTask.execute(...);      //wait for task code     // Robolectric.runBackgroundTasks(); (pre 3.0)     Robolectric.flushBackgroundThreadScheduler(); //from 3.0      //can run asserts on result now     assert...(asyncTask.get()); } 
like image 77
weston Avatar answered Sep 21 '22 14:09

weston


With Robolectric 2.4 this is now in ShadowApplication:

ShadowApplication.runBackgroundTasks();

like image 45
Felipe Lima Avatar answered Sep 21 '22 14:09

Felipe Lima