The Science Boy The Science Boy - 5 months ago 24
Android Question

How do I run code in the UI thread in an Android JUnit test without an Activity?

I have a database component that relies on

AsyncTask
to retrieve data. Once used in the application it will always be called from the UI thread, but how do I do that in the JUnit tests without instantiating an
Activity
(i just don't have an activity, nor should I have to create one just for testing purposes)?

runOnUiThread()
is an activity method so it's not an option. Is there a way to simulate the UI thread eiether by getting one from the Android test library or by implementing a MockUiThread?

Answer

Android.OS.Handler should be able to update the ui.

To use a handler you have to subclass it and overide handleMessage() to process messages

Update:

I am using monodroid, so I dont know if this is completely translatable, But,

You may be able to use

new Handler(context.getMainLooper()).post(runnable);
Comments