How to interact with alertdialog in Espresso?

1.5k views Asked by At

I have a test in which I have a Alertdialog on which there is an "input" field and buttons "Cancel"(id is button2) and "Ok"(id is button1). First I have to enter the value "1234" in the field, and then click on the "Ok" button. But it doesn’t work for me, the test fails.

    onView(withId(R.id.input)).perform(typeText("1234"));
    closeSoftKeyboard();
    click(R.id.button1);
    Thread.sleep(5000);
1

There are 1 answers

6
jeprubio On

You should use the the isDialog() RootMatcher:

onView(allOf(
       isDescendantOfA(withId(R.id.input)),
       isAssignableFrom(EditText.class)))
    .inRoot(isDialog())
    .perform(typeText("1234"))
    .perform(closeSoftKeyboard());
onView(withText("Ok"))
    .inRoot(isDialog())
    .check(matches(isDisplayed()))
    .perform(click());
Thread.sleep(5000);