我已经寻找解决方案,但找不到。 我正在创建一个 Espresso 测试,并需要关闭弹出在特定活动屏幕首次显示时出现在屏幕中央的警示对话框。 对话框上没有按钮,因此要关闭它,用户需要单击框外的任何地方。 有人知道我如何使用 Espresso 实现这一点。 我尝试在底层屏幕上点击布局,但 Espresso 失败并显示该视图未在层次结构中找到。
我已经寻找解决方案,但找不到。 我正在创建一个 Espresso 测试,并需要关闭弹出在特定活动屏幕首次显示时出现在屏幕中央的警示对话框。 对话框上没有按钮,因此要关闭它,用户需要单击框外的任何地方。 有人知道我如何使用 Espresso 实现这一点。 我尝试在底层屏幕上点击布局,但 Espresso 失败并显示该视图未在层次结构中找到。
使用onView(withText("alert_dialog_text")).perform(pressBack());
这条语句可以关闭对话框。
首先检查弹出框是否显示,如果是,则执行“返回”点击事件。
onView(withText("OK")).inRoot(isDialog()).check(matches(isDisplayed())).perform(pressBack());
将“OK”文本替换为对话框显示的文本。
Espresso无法做到这一点。
您需要在Espresso测试中使用uiautomator,将以下内容添加到项目的gradle中:
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
当您的对话框出现后,您可以在屏幕上任何坐标点击:
UiDevice device = UiDevice.getInstance(getInstrumentation());
device.click(x,y);
这将关闭您的对话框
正如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.
AndroidX
时,该依赖项的格式为 androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
。 - sunadorer我在我的端上尝试了一下,你只需要调用pressBack()函数。我曾经遇到过同样的情况,这个方法对我很有帮助。如果这个方法对你没有帮助,我们可以交流一下,我会帮助你的。 祝你好运!
perform()
需要一个ViewAction
,而Espresso.pressBack()
返回void
。您需要添加更多细节吗? - kishu27