Testing async tasks with robolectric

2019-02-08 03:03发布

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

2条回答
疯言疯语
2楼-- · 2019-02-08 03:13

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());
}
查看更多
冷血范
3楼-- · 2019-02-08 03:20

With Robolectric 2.4 this is now in ShadowApplication:

ShadowApplication.runBackgroundTasks();

查看更多
登录 后发表回答