Espress - 访问线性布局的第n个子元素

时间:2016-08-04 17:26:46

标签: android automated-tests android-espresso android-instrumentation

在espresso中,我试图访问线性布局的第3个子元素。 见附件截图。

enter image description here

我尝试了一些匹配器,但没有让它工作。

1 个答案:

答案 0 :(得分:0)

您需要创建自定义匹配器:

 public static Matcher<View> nthChildOf(final Matcher<View> parentMatcher, final int childPosition) {
    return new TypeSafeMatcher<View>() {
      @Override
      public void describeTo(Description description) {
        description.appendText("with "+childPosition+" child view of type parentMatcher");
      }

      @Override
      public boolean matchesSafely(View view) {
        if (!(view.getParent() instanceof ViewGroup)) {
              return parentMatcher.matches(view.getParent());
        }

        ViewGroup group = (ViewGroup) view.getParent();
        return parentMatcher.matches(view.getParent()) && group.getChildAt(childPosition).equals(view);
      }
    };
  }

使用它:

onView(nthChildOf(withId(R.id.directParentLinearLayout), 0).check(matches(withText("I am the first child"));

在您的情况下,您还需要检查具有唯一ID的布局的后代:

onView(nthChildOf(allOf(withId(R.id.directParentLinearLayout), isDescendantOfA(withId(R.id.linearLayoutWithUniqueId))), 0).check(matches(withText("I am the first child"));