Dismiss Alert Dialog in Android Espresso Test

2019-06-23 16:18发布

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条回答
放我归山
2楼-- · 2019-06-23 16:39

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-06-23 16:40

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

查看更多
闹够了就滚
4楼-- · 2019-06-23 16:53

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

查看更多
太酷不给撩
5楼-- · 2019-06-23 16:55

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!

查看更多
Lonely孤独者°
6楼-- · 2019-06-23 17:01

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

查看更多
登录 后发表回答