首页 > 解决方案 > 尝试单击切换框时出现 Espresso AmbiguousViewMatcherException

问题描述

当我尝试在测试下运行时,我得到了 AmbiguousViewMatcherException,我怎样才能从多个视图中获得预期的视图。

   ViewInteraction switch_ = onView(
            allOf(withClassName(is("android.widget.Switch"))
                    childAtPosition(
                            allOf(withId(android.R.id.widget_frame),
                                    childAtPosition(
                                            withClassName(is("android.widget.LinearLayout")),
                                            2)),
                            0),
                    isDisplayed()));
    switch_.perform(click());

它给了我以下两个开关 id 匹配的异常

Switch{id=16909051, res-name=switchWidget, visibility=VISIBLE, width=136, height=51, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=6.0, text=, input-type=0, ime-target=false, has-links=false, is-checked=false} ****MATCHES**


Switch{id=16909051, res-name=switchWidget, visibility=VISIBLE, width=136, height=51, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=6.0, text=, input-type=0, ime-target=false, has-links=false, is-checked=false} ****MATCHES****

我曾尝试使用 hasfocus()、withEffectiveVisibility(VISIBLE) 方法但无法解决问题。

有人可以帮忙吗?

标签: androidexceptionandroid-espressoandroid-testing

解决方案


以下方法解决了我的问题。

现在使用 index 方法访问具有相同 id 的多个视图。

 public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) {
    return new TypeSafeMatcher<View>() {
        int currentIndex = 0;

        @Override
        public void describeTo(Description description) {
            description.appendText("with index: ");
            description.appendValue(index);
            matcher.describeTo(description);
        }

        @Override
        public boolean matchesSafely(View view) {
            return matcher.matches(view) && currentIndex ++== index;
        }
    };
}

在定义方法之后,只需将此行添加到测试用例中以访问正确的开关帧

onView(withIndex(withId(android.R.id.widget_frame), 3)).perform(click());

推荐阅读