如何在对话框浓缩咖啡中找到按钮

How to find button in dialog espresso

我有这个弹出窗口。我怎样才能按下退出按钮?

我这样使用字符串:

onView(withId(android.R.id.button1)).perform((click()));  

enter image description here

尝试:

onView(withText("QUIT"))
    .inRoot(isDialog())
    .check(matches(isDisplayed()))
    .perform(click());

如果您将 UI-Automator 与 AndroidX 一起使用,您可以找到对话框和按钮。

这是一个gradle依赖代码。

dependencies {
    androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}

您可以使用此代码到达 QUIT 按钮。

这是 Kotlin 代码。

val button = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
                .findObject(
                    UiSelector().text(
                        activityTestRule
                            .activity
                            .getString(R.string.quit_button)
                            .toUpperCase()
                    )
                )

if (button.exists() && button.isEnabled) {
    button.click()
}