尝试单击开关框时,Espresso AmbiguousViewMatcherException

时间:2018-07-10 21:29:45

标签: android exception android-espresso android-testing

当我尝试在测试下运行时,出现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()和EffectiveVisibility(VISIBLE)方法,但无法解决问题。

有人可以在这里帮忙吗?

1 个答案:

答案 0 :(得分:0)

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

现在可以使用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());