How to use espresso to press a AlertDialog button
According to StackOverflow
similar issue: Check if a dialog is displayed with Espresso
You should change your code from:
onView(withText("GA NAAR INSTELLINGEN")).perform(click());
to
onView(withText("GA NAAR INSTELLINGEN")))
.inRoot(isDialog()) // <---
.check(matches(isDisplayed()))
.perform(click());
If it won't work, don't bother to use long with Espresso
another great Google's instrumentation test called uiatomator
.
Check: http://qathread.blogspot.com/2015/05/espresso-uiautomator-perfect-tandem.html
Example code:
// Initialize UiDevice instance
UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// Search for correct button in the dialog.
UiObject button = uiDevice.findObject(new UiSelector().text("GA NAAR INSTELLINGEN"));
if (button.exists() && button.isEnabled()) {
button.click();
}
Hope it will help
Since inRoot(isDialog())
does not seem to work for DialogFragment
I use this workaround so far:
enum class AlertDialogButton(@IdRes val resId: Int) {
POSITIVE(android.R.id.button1),
NEGATIVE(android.R.id.button2),
NEUTRAL(android.R.id.button3)
}
fun clickOnButtonInAlertDialog(button: AlertDialogButton) {
onView(withId(button.resId)).perform(click())
}
For an AlertDialog
, the id assigned for each button is:
- POSITIVE:
android.R.id.button1
- NEGATIVE:
android.R.id.button2
- NEUTRAL:
android.R.id.button3
You can check yourself in the AlertController
class, setupButtons()
method.
So you can perform a click as follows:
onView(withId(android.R.id.button1)).perform(click());