首页 > 解决方案 > 如何与 Espresso 中的 alertdialog 交互?

问题描述

我有一个测试,其中有一个 Alertdialog,其中有一个“输入”字段和按钮“取消”(id 是 button2)和“Ok”(id 是 button1)。首先,我必须在字段中输入值“1234”,然后单击“确定”按钮。但这对我不起作用,测试失败。

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

标签: testingandroid-espressobarista

解决方案


您应该使用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);

推荐阅读