I'm writing UI tests for my application using Espresso. I'd like to test the fact that if I click the back button while a server request is in progress the app must remain where it is.
It seems not to be possible due to the espresso's architecture that makes the tests execution wait if some background operation (like AsyncTask) has been fired.
So, how can I test the following scenario:
- click on a button that fires an AsyncTask
- test that while the task is running and I press back button, the app stays there?
Is it possibile?
thank you
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,