Android jUnit test for asynchronous tasks

24 03 2012

Android dialog is example of using asynchronous background tasks in Android. In my case it was downloading data from server and a dialog box with “Please wait…” text. Here is a good AsyncTask example, and below – how it goes in my case:

  1. AsyncTask is started in activity OnStart() along with showing dialog box
  2. Data is being downloaded in inner class extending AsyncTask
  3. After data is downloaded the dialog box is dismissed and further data processing initialized (in the OnPostExecute() method)

Everything works very well until it comes to jUnit testing. The cause is dialog box invocation that throws an exception:

java.lang.IllegalArgumentException: View not attached to window manager

The cause is that displaying and hiding dialog box causes updating the activity, so the activity must exist also when dialog box is being dismissed.

jUnit test is running so fast that the activity is being destroyed before the dialog box is dismissed in AsyncTask. Then it would be great to hold on the test execution (even if everything was already tested) until the dialog box will disapear and then destroy the whole activity. The solution is small lib – Awaitility.

Awaitility enables to wait until some condition is met or the timer is exceeded. So there is possibility to check if dialog box was dismissed and hold test execution until it happens – with few lines of code. See the simpliest samples from Awaitility site.

In my case I used just:


along with a flag in tested activity, indicating if data downloading has finished. dataIsDownloaded() just checks if this flag is set to true. I put this lin of code in tearDown() method, as data downloaded is not needed for my test – i just have to wait for a dialog box to be dismissed until finishing the activity under tests.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!



3 responses

24 03 2012

Thanks for sharing this tip, as soon I want start learning jUnit too.

24 03 2012
Jacek Milewski

This is just a small part of jUnit, in fact a bit aside of it :)

Probably You will be interested in my older post with android TDD Tutorials. You will find a lot of jUnit info there

24 03 2012

Thanks, I’ll take a look.

Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: