AsyncTask test fails

I use robolectric to test the AsyncTask class. In the test, it does what I expect when the task runs as follows:

asyncTask.execute() 

But when I do

 asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) 

no (in both cases I run

 Robolectric.runUiThreadTasksIncludingDelayedTasks() 

Does anyone have an idea why calling executeOnExecutor does not start Robolectric to start, but the execution is working fine?

+5
source share
1 answer

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 { // ... test code } 

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).

+12
source

Source: https://habr.com/ru/post/1204389/


All Articles