How to interact with alertdialog in Espresso?

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);

Upvotes: 1

Views: 1723

Answers (1)

jeprubio
jeprubio

Reputation: 18032

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);

Upvotes: 2

Related Questions