android - 尝试单击切换框时出现 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) 方法但无法解决问题。
有人可以帮忙吗?
解决方案
以下方法解决了我的问题。
现在使用 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());
推荐阅读
- python - 如何在 Beautiful Soup 中的标签上使用 if 语句?
- git - 如何在git中自动排除某些文件类型?
- facebook - 无法在 Facebook Business Manager 中访问 Whatsapp Manager
- c++ - C ++复制构造函数,用于指向对象的指针数组
- assembly - 在程序集中调用多个标签/函数的问题
- python - 频率分布数据框中的所有值
- javascript - 如何使用 Javascript 而不是 CSS 来检索元素(图像)的位置?
- algorithm - B-Tree保存在File中的好处不是就丢失了吗?
- docker - Docker 服务:由于不支持 IPv6,无法使用浏览器连接到 localhost
- filesystems - 修改原始磁盘会损坏文件系统吗?