0

我遇到了一个问题,我试图在我的setUp()方法中更改 UI。

public class DrawerRootActivityTest extends android.test.ActivityInstrumentationTestCase2<DrawerRootActivity> {

    @UiThreadTest
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        rootActivity = (DrawerRootActivity) getActivity();
        cf = rootActivity.calculatorFragment;
        cf.changeDigitDisplay(2); // Line 29
    }

}

这是测试控制台:

Running tests
Test running started
android.view.ViewRootImpl$CalledFromWrongThreadException: 
    Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6024)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:853)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4320)
at android.view.View.invalidate(View.java:10935)
at android.view.View.invalidate(View.java:10890)
...
com.mydomain.myapp.DrawerRootActivityTest.setUp(DrawerRootActivityTest.java:29)

我需要在setUp()触发将更新 UI 的副作用的方法中对我的应用程序进行一些更改。我认为添加@UiThreadTest 注释会导致它在主 ui 线程上运行。

我应该以不同的方式做到这一点吗?

4

1 回答 1

1

试试这个:

protected void setUp() throws Exception {
    super.setUp();
    rootActivity = (DrawerRootActivity) getActivity();
    rootActivity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            cf = rootActivity.calculatorFragment;
            cf.changeDigitDisplay(2); // Line 29
            }
    });
}
于 2015-06-26T06:31:24.743 回答