Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss Alert Dialog in Android Espresso Test

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.

like image 242
Richard Shergold Avatar asked Jul 08 '15 09:07

Richard Shergold


People also ask

What's the difference between dialog and AlertDialog in Android?

AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .

How do I record espresso test on Android?

Record UI interactionsClick Run > Record Espresso Test. In the Select Deployment Target window, choose the device on which you want to record the test. If necessary, create a new Android Virtual Device. Click OK.

What is espresso in mobile testing?

Espresso created by Google is a native framework for Android automated testing. The tool is a part of the Android SDK and is easy to use for native mobile development. Thanks to Espresso, you can create tests that are close to the Android app's logic.

What is espresso used for Android?

Use Espresso to write concise, beautiful, and reliable Android UI tests. The core API is small, predictable, and easy to learn and yet remains open for customization.


3 Answers

Use onView(withText("alert_dialog_text")).perform(pressBack()); this must dismiss your dialog.

like image 100
denys Avatar answered Sep 24 '22 12:09

denys


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

like image 33
ked Avatar answered Sep 24 '22 12:09

ked


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

like image 28
Rubén López García Avatar answered Sep 22 '22 12:09

Rubén López García