Testing Android devices with AsyncTask and UI Updates

Scenario:

I am trying the unit test onClick handler of my application. Onclick performs a simple REST API search, returns results, and updates the user interface.

More details:

Onclick runs AsyncTask, doInBackground requests the REST API and returns the results. OnPostExecute takes the results and assigns a new ListAdapter to the ListView with the data.

Problem:

OnPostExecute does not receive the call in Test Runner because it is in the same UI thread and blocks the call. There are several ways to deal with this. However, if I put AsyncTask in Runnable and use LatchCountdown to wait for the result, I get a CalledFromWrongThread exception.

Is there a good AsyncTask unit test solution that updates the UI? Or a more testable design that I can implement?

+6
source share
2 answers

So, the solution I came up with is the following:

1.) Define a listener interface for pre and post events.
2.) Implement a listener by activity
2.) Define a task wrapper class that accepts a listener and that has an internal AsyncTask that is called in 'exec'.
3.) Internal AsyncTask notifies the listener of onPreExecute and onPostExecute
4.) After notification, the activity updates its user interface.

For testing in Office:
1.) Create a serial version of the wrapper class by inheriting from it, and then override the exec method to execute in sequence:
- notify the listener about the task as starting.
- to perform the task.
- notify the listener that the task has been completed.

To test the asynchronous version of the task.
1.) Use CountdownLatch and Runnable in the unit test method. Since there will be no UI updates, you will not have any WrongThreadExceptions errors.

0
source

Do you want to run the test in Ui Thread

runOnUiThread(new Runnable() { public void run() { onPostExecute(...) } }); 
0
source

All Articles