Android Instrumentation Testing - UI Thread Issues

前端 未结 5 1024
走了就别回头了
走了就别回头了 2020-12-30 22:16

I am trying to write an Instrumentation Test for my Android app.

I\'m running into some weird threading issues and I can\'t seem to find a solution.

My

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 22:36

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

    @Rule
    public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
    
    @Test
    public 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)).

提交回复
热议问题