Android Instrumentation Testing - UI Thread Issues Android Instrumentation Testing - UI Thread Issues multithreading multithreading

Android Instrumentation Testing - UI Thread Issues


Those instrumentation tests run inside their own app. This also means, they run in their own thread.

You must think of your instrumentation as something you install alongside your actual app, so your possible interactions are 'limited'.

You need to call all view methods from the UIThread / main thread of the application, so calling activity.updateDetails(workOrder); from your instrumentation thread is not the application main thread. This is why the exception is thrown.

You can just run the code you need to test on your main thread like you would do if you were calling it inside your app from a different thread by using

activity.runOnUiThread(new Runnable() {    public void run() {        activity.updateDetails(workOrder);    }}

With this running your test should work.

The illegal state exception you are receiving seems to be because of your interaction with the rule. The documentation states

Note that instrumentation methods may not be used when this annotation is present.

If you start / get your activity in @Before it should also work.


You can run portion of your test on the main UI thread with the help of UiThreadTestRule.runOnUiThread(Runnable):

@Rulepublic UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();@Testpublic void loadWorkOrder_displaysCorrectly() throws Exception {    final WorkOrderDetails activity = activityRule.getActivity();    uiThreadTestRule.runOnUiThread(new Runnable() {        @Override        public void run() {            WorkOrder workOrder = new WorkOrder();            activity.updateDetails(workOrder);        }    });    //Verify customer info is displayed    onView(withId(R.id.customer_name))            .check(matches(withText("John Smith")));}

In most cases it is simpler to annotate the test method with UiThreadTest, however, it may incur other errors such as java.lang.IllegalStateException: Method cannot be called on the main application thread (on: main).

FYR, here is a quote from UiThreadTest's Javadoc:

Note, due to current JUnit limitation, methods annotated with Before and After will also be executed on the UI Thread. Consider using runOnUiThread(Runnable) if this is an issue.

Please note UiThreadTest (package android.support.test.annotation) mentioned above is different from (UiThreadTest (package android.test)).


The accepted answer is now deprecated

The easiest way to achieve this is simply using UiThreadTest

import android.support.test.annotation.UiThreadTest;        @Test        @UiThreadTest        public void myTest() {            // Set up conditions for test            // Call the tested method            activity.doSomethingWithAView()            // Verify that the results are correct        }