Robolectric, AsyncTasks and Threads
I recently started using Robolectric to test some of my Android apps and ran into a problem. I use AsyncTasks in a couple of places to do some background calculations and then update the UI based on the result of those calculations. If I use execute()
to call AsyncTask when I run my tests to check if the UI is updated correctly, it passes. However, for various reasons, I use exectueOnExecutor()
with a parameter THREAD_POOL_EXECUTOR
. When I run tests with this, the tests fail, thinking the UI is not up to date. Likewise, if I do it from a thread and post back to the UI thread, I have the same problem. Is there a way to get around this?
source to share
After hours of searching, this thread helped me solve my problem. In simple steps, you should create a new class that shadows your AsyncTasks that are using executeOnExecutor()
what seems to be a bug in the Robolectric structure. Here's an example from the above thread:
@Implements(AsyncTask.class)
public class MyShadowAsyncTask<Params, Progress, Result> extends ShadowAsyncTask<Params, Progress, Result> {
@RealObject private AsyncTask<Params, Progress, Result> realAsyncTask;
@Implementation
public AsyncTask<Params, Progress, Result> executeOnExecutor(Executor executor, Params... params) {
return super.execute(params);
}
}
Apart from changing the class name, I don't need to change anything to get it working. The last step is to simply annotate your test class with
@Config(shadows={MyShadowAsyncTask.class})
Works great for me.
source to share