I've looked around for solution for this but can't find one. I'm creating an Espresso Test and need to dismiss an Alert Dialog that appears in the middle of the screen the first time a particular Activity screen is displayed. There are no buttons on the dialog so to dismiss it the user needs to click anywhere outside the box. Does anyone know how I can do this with Espresso. I tried clicking on a layout on the underlying screen but Espresso fails saying that view cannot be found in the hierarchy.
5 Answers
Use onView(withText("alert_dialog_text")).perform(pressBack());
this must dismiss your dialog.

- 6,834
- 3
- 37
- 36
-
3`perform()` requires a `ViewAction` and `Espresso.pressBack()` returns `void`. Would you like to add more details? – kishu27 Apr 25 '17 at 17:33
-
1Use: ViewActions.pressBack() – Leandro Borges Ferreira Oct 29 '19 at 11:30
first check if the alert dialog is shown, if yes then perform pressBack click event
onView(withText("OK")).inRoot(isDialog()).check(matches(isDisplayed())).perform(pressBack());
replace the OK text with the text displayed on dialog

- 2,426
- 21
- 24
Espresso can't do this.
You need to use uiautomator inside your Espresso test, add this to your project's gradle:
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
After your dialog appears, you can click on the screen at any coordinate:
UiDevice device = UiDevice.getInstance(getInstrumentation());
device.click(x,y);
That will close your dialog

- 111
- 1
- 5
As Ruben already mentioned in previous answers, this looks like an issue to consider using UIAutomator. With Espresso, you can operate only inside your application context whereas UIAutomator gives you the control of your test device.
Add dependency to project's build.gradle
dependencies { androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' }
Following code block checks if the dialog with certain text exists in the screen, then dismisses it by pressing back button.
UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); UiObject uiObject = mDevice.findObject(new UiSelector().text("TEXT TO CHECK")); if (uiObject.exists()) { mDevice.pressBack(); }
Note: This framework requires Android 4.3 (API level 18) or higher.

- 507
- 4
- 15
-
3Using `AndroidX` the dependency looks like this `androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"` – sunadorer May 21 '19 at 15:52
I tried on my end and you just need to call pressBack() . I had the same situation and this helped me a lot. If this is not helping you, we can talk and I will help you. Good luck!

- 1,999
- 1
- 20
- 25