我正在使用 Espresso 为我的应用程序编写 UI 测试。我想测试一个事实,如果我在服务器请求正在进行时单击后退按钮,应用程序必须保持原样。
由于 espresso 的架构,如果某些后台操作(如 AsyncTask)被触发,测试执行将等待,这似乎是不可能的。
那么,我如何测试以下场景:
有可能吗?
谢谢你
最佳答案
这很棘手。使用 AsyncTasks
您不能在任务运行时使用 Espresso。
如果您要使用其他东西进行后台工作,Espresso 不会等待,并且测试会在后台工作之前完成。
一个简单的解决方法是在任务运行时在没有 Espresso 的情况下“按下”后退按钮。因此,启动任务,调用 Activity.onBackPressed()
并在任务完成后使用 Espresso 检查 Activity
是否仍然可见:
// Start the async task
onView(withId(R.id.start_task_button)).perform(click());
// Then "press" the back button (in the ui thread of the app under test)
mActivityTestRule.runOnUiThread(new Runnable() {
@Override
public void run() {
mActivityTestRule.getActivity().onBackPressed();
}
});
// Then check that the Activity is still visible
// (will be performed when the async task has finished)
onView(withId(R.id.any_view_on_activity)).check(matches(isDisplayed()));