Testing async tasks with robolectric

前端 未结 2 1113
无人共我
无人共我 2021-01-01 12:27

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

2条回答
  •  死守一世寂寞
    2021-01-01 13:07

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

提交回复
热议问题