【发布时间】:2016-05-13 01:25:11
【问题描述】:
我正在尝试为我的 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: 无法在主应用程序线程(on: main)上调用方法
(注意:此堆栈跟踪中的所有方法都不是我的代码)
这似乎给了我混合的结果...如果它需要在创建视图的原始线程上运行但不能在主线程上运行,它应该在哪个线程上运行?
非常感谢任何帮助或建议!
【问题讨论】:
标签: java android multithreading testing junit