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 instanceUiDevice 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())}
You might need to close the softkeyboard like this:
onView(withId(R.id.username)) .perform(typeText("username")) .perform(closeSoftKeyboard()) onView(withId(android.R.id.button1)).perform((click()))
As detailed more thoroughly by this answer.