Espresso test back button while AsyncTask is running

情到浓时终转凉″ 提交于 2019-12-06 03:14:18

That's tricky. With AsyncTasks you cannot use Espresso while the tasks are running. And if you would use something else for background work, Espresso does not wait, and the test finishes before the background job.

A simple workaround would be to "press" the back button without Espresso while the task is running. So, start the task, call Activity.onBackPressed() and after the task finishes use Espresso to check that the Activity is still visible:

// 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()));

You can prevent the application from triggering finish() when the back button is pressed. To do so, just override public void onBackPressed() without calling super.onBackPressed(). Just like :

@Override
public void onBackPressed() {
  // super.onBackPressed();
}

Additionally, if you are showing a dialog while executing the task, you can use

myDialog.setCancelable(false);
myDialog.setCanceledOnTouchOutside(false);

to prevent the button from being pushed.

Regards,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!