安卓工具测试 - UI 线程问题
我正在尝试为我的 Android 应用编写检测测试。
我遇到了一些奇怪的线程问题,我似乎找不到解决方案。
我的原始测试:
@RunWith(AndroidJUnit4.class)
public class WorkOrderDetailsTest {
@Rule
public ActivityTestRule<WorkOrderDetails> activityRule = new ActivityTestRule<>(WorkOrderDetails.class);
@Test
public void loadWorkOrder_displaysCorrectly() throws Exception {
final WorkOrderDetails activity = activityRule.getActivity();
WorkOrder workOrder = new WorkOrder();
activity.updateDetails(workOrder);
//Verify customer info is displayed
onView(withId(R.id.customer_name))
.check(matches(withText("John Smith")));
}
}
这导致了一个
android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。
...
com.kwtree.kwtree.workorder.WorkOrderDetails.updateDetails(WorkOrderDetails.java:155)
该方法唯一要做的就是一些调用。updateDetails()
setText()
经过一些研究,似乎在我的测试中添加一个和注释可以解决这个问题。UiThreadTestRule
android.support.test.annotation.UiThreadTest
@UiThreadTest:
@RunWith(AndroidJUnit4.class)
public class WorkOrderDetailsTest {
//Note: This is new
@Rule
public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
@Rule
public ActivityTestRule<WorkOrderDetails> activityRule = new ActivityTestRule<>(WorkOrderDetails.class);
@Test
@UiThreadTest //Note: This is new
public void loadWorkOrder_displaysCorrectly() throws Exception {
final WorkOrderDetails activity = activityRule.getActivity();
WorkOrder workOrder = new WorkOrder();
activity.updateDetails(workOrder);
//Verify customer info is displayed
onView(withId(R.id.customer_name))
.check(matches(withText("John Smith")));
}
}
java.lang.IllegalStateException:方法不能在主应用程序线程上调用(在:main上)
(注意:此堆栈跟踪中的所有方法都不是我的代码)
它似乎给了我好坏参半的结果...如果它需要在创建视图的原始线程上运行,但不能在主线程上运行,那么它应该在哪个线程上运行?
我真的非常感谢任何帮助或建议!