The Robolectric frame cannot work out of the box with default executors (for example, AsyncTask.THREAD_POOL_EXECUTOR or AsyncTask.SERIAL_EXECUTOR), as well as with custom ones.
To solve this problem, you can take one of these two approaches, depending on whether you have control over the performer that the unit under test uses. If the answer is βYES,β the first approach would be to simply force him to use RoboExecutorService (or, if you use versions under 3.0, RobolectricBackgroundExecutorService ). Otherwise, you will have to take a different approach, which is to apply this two-line workaround:
Defining a custom AsyncTask shadow
The first thing you need to do is implement the AsyncTask shadow, which overrides execution for custom artists:
@Implements(AsyncTask.class) public class MyShadowAsyncTask<Params, Progress, Result> extends ShadowAsyncTask<Params, Progress, Result> { @Implementation public AsyncTask<Params, Progress, Result> executeOnExecutor(Executor executor, Params... params) { return super.execute(params); } }
Custom Shadow Registration
In each test case that runs production code that uses AsyncTask#executeOnExecutor() , register your own shadow to override Robolectric default, this way (see the βconfigβ annotation):
@RunWith(RobolectricTestRunner.class) @Config(shadows={MyShadowAsyncTask.class}) public class MyTest {
Subsequent calls to Robolectric.runUiThreadTasks() or Robolectric.runUiThreadTasksIncludingDelayedTasks() will work as you expected (namely, they would block the flow of runners until the completion of asynchronous tasks).
source share