我遇到了一个问题,我试图在我的setUp()
方法中更改用户界面。
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线程上运行。
我应该以不同的方式做这件事吗?
答案 0 :(得分: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
}
});
}