在Android Espresso测试中关闭提示对话框

11

我已经寻找解决方案,但找不到。 我正在创建一个 Espresso 测试,并需要关闭弹出在特定活动屏幕首次显示时出现在屏幕中央的警示对话框。 对话框上没有按钮,因此要关闭它,用户需要单击框外的任何地方。 有人知道我如何使用 Espresso 实现这一点。 我尝试在底层屏幕上点击布局,但 Espresso 失败并显示该视图未在层次结构中找到。

5个回答

25

使用onView(withText("alert_dialog_text")).perform(pressBack());这条语句可以关闭对话框。


3
perform() 需要一个 ViewAction,而 Espresso.pressBack() 返回 void。您需要添加更多细节吗? - kishu27
1
使用:ViewActions.pressBack() - Leandro Borges Ferreira

7

首先检查弹出框是否显示,如果是,则执行“返回”点击事件。

onView(withText("OK")).inRoot(isDialog()).check(matches(isDisplayed())).perform(pressBack());

将“OK”文本替换为对话框显示的文本。


4

Espresso无法做到这一点。

您需要在Espresso测试中使用uiautomator,将以下内容添加到项目的gradle中:

androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'

当您的对话框出现后,您可以在屏幕上任何坐标点击:

UiDevice device = UiDevice.getInstance(getInstrumentation());
        device.click(x,y);

这将关闭您的对话框


4

正如Ruben在之前的回答中提到的那样,这似乎是考虑使用UIAutomator解决的问题。使用Espresso,您只能在您的应用程序上下文中操作,而UIAutomator可以让您控制测试设备。

  • 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.


3
使用 AndroidX 时,该依赖项的格式为 androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0" - sunadorer

0

我在我的端上尝试了一下,你只需要调用pressBack()函数。我曾经遇到过同样的情况,这个方法对我很有帮助。如果这个方法对你没有帮助,我们可以交流一下,我会帮助你的。 祝你好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接