1

我正在为带有复选框的溢出菜单的 UI 编写测试,如下图所示。我想检查每个复选框的状态,并切换它们,但我无法找到匹配它们的方法。复选框及其标签是不同的视图,因此我无法将复选框与withText()并且hasSibling()也不起作用。由于布局是由菜单框架生成的,我无法控制复选框的 id(它们都有 id“复选框”)。

这是菜单的样子:

在此处输入图像描述

这是我尝试匹配和切换复选框。它失败了NoMatchingViewException

private static void toggleMenu(String label, boolean initial) {
    openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
    ViewInteraction v = onView(allOf(instanceOf(CheckBox.class), hasSibling(withText(label)), isCompletelyDisplayed()));
    if(initial)
        v.check(matches(isChecked()));
    else
        v.check(matches(not(isChecked())));
    v.perform(click());
    openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
    v = onView(allOf(instanceOf(CheckBox.class), hasSibling(withText(label)), isCompletelyDisplayed()));
    if(!initial)
        v.check(matches(isChecked()));
    else
        v.check(matches(not(isChecked())));
    pressBack();
}
4

1 回答 1

1

所以事实证明,标签在复选框的层次结构中向下一层,复选框的兄弟姐妹的子级也是如此。所以找到复选框并切换它的代码变成了这样:

private static void toggleMenu(String label, boolean initial) {
    openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
    ViewInteraction v = onView(allOf(instanceOf(CheckBox.class), hasSibling(withChild(withText(label))), isCompletelyDisplayed()));
    if(initial)
        v.check(matches(isChecked()));
    else
        v.check(matches(not(isChecked())));
    v.perform(click());
    openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
    v = onView(allOf(instanceOf(CheckBox.class), hasSibling(withChild(withText(label))), isCompletelyDisplayed()));
    if(!initial)
        v.check(matches(isChecked()));
    else
        v.check(matches(not(isChecked())));
    pressBack();
}
于 2017-11-24T00:04:34.143 回答