尝试单击图标(TextView)时出现 Espresso AmbiguousViewMatcherException

Espresso AmbiguousViewMatcherException when trying to click a icon (TextView)

LinearLayout (productList) 在运行时动态填充子视图,如下所示:

@ViewById(R.id.ll_products)
LinearLayout productList;

public void createProductList() {
    productList.addView(getView(mobilePhone))
    productList.addView(getView(internet))
    productList.addView(getView(television))
}

public View getView(Product product) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    TextView layout = (LinearLayout) inflater.inflate(R.layout.row_product, null);
    TextView productIcon = (TextView) layout.findViewById(R.id.tv_product_row_icon);
    productIcon.setText(product.getProductIcon());
    productName.setText(product.getName());
}

productList 故意是 LinearLayout,不是 ListView。

产品列表包含三个产品 - 每个产品都有图标(可能重复)。

我想记录一个场景,我点击了第二个产品的图标。 这样的场景如何避免AmbiguousViewMatcherException?

不幸的是,以下代码将不起作用 - 将找到三个 R.id.tv_product_row_icon...

    ViewInteraction appCompatTextView = onView(withId(R.id.tv_product_row_icon));
    appCompatTextView.perform(scrollTo(), click());

如何指定点击第二个图标?

不幸的是,您必须为这种情况创建自定义 Matcher

以下匹配具有指定索引的 View

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;
        }
    };
}

适合您的情况的用法:

Matcher<View> secondIconMatcher = allOf(withId(R.id.tv_product_row_icon));
onView(withIndex(secondIconMatcher , 1)).perform(click());