如何获取在 android 测试中没有 id 的视图的子视图

How to get the child of a view which is not having an id in android test

我想在测试期间通过单击汉堡包菜单 打开导航抽屉。

目前action bar的层级如下:

...
Toolbar (@id/action_bar)
  TextView (no-id)
  ImageButton (no-id) <-- this is the hamburger menu
  ...
...

使用 Espresso 时只有 withIdwithText 等匹配器,这不符合我的目的。

好的,原来使用自定义 ViewMatcher 就可以了:

此处匹配器必须匹配一个视图,该视图的父级 ID 为 action_bar,并且是一个 ImageView。

onView(childOf(withId(android.support.v7.appcompat.R.id.action_bar),
            withClassName(is(ImageButton.class.getName()))))
            .perform(click());

方法childOf如下:

Matcher<View> childOf(Matcher<View> parentMatcher,
        Matcher<View> childMatcher) {
    return new TypeSafeMatcher<View>() {
        @Override
        public void describeTo(Description description) {
             // creation of description left as an exercise
        }

        @Override
        protected boolean matchesSafely(View view) {
            if (view.getParent() instanceof ViewGroup) {
                ViewGroup parent = (ViewGroup) view.getParent();
                return parentMatcher.matches(parent) && childMatcher
                        .matches(view);
            }
            return false;
        }
    };
}

该方法允许使用多种子ViewMatcher,因此您可以根据需要使用自定义视图匹配器。

参考文献:

  1. 浓咖啡custom-matcher sample

您可以结合使用 allOfwithParent 来确定该视图:

onView(
    allOf(
      withClassName(is(ImageButton.class.getName())),
      withParent(withId(android.support.v7.appcompat.R.id.action_bar)))
  .perform(click());

更多信息:http://blog.sqisland.com/2015/05/espresso-match-toolbar-title.html