Testing async tasks with robolectric

霸气de小男生 提交于 2019-11-30 10:57:48

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());
}

With Robolectric 2.4 this is now in ShadowApplication:

ShadowApplication.runBackgroundTasks();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!