Richard Shergold
Richard Shergold

Reputation: 632

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.

Upvotes: 11

Views: 13229

Answers (5)

Fatih
Fatih

Reputation: 605

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.

Upvotes: 5

ked
ked

Reputation: 2456

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

Upvotes: 8

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

Upvotes: 5

sunlover3
sunlover3

Reputation: 2049

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!

Upvotes: 0

denys
denys

Reputation: 6910

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

Upvotes: 25

Related Questions