代码之家  ›  专栏  ›  技术社区  ›  David Silva

尝试单击图标时出现Espresso模糊ViewMatcherException(文本视图)

  •  0
  • David Silva  · 技术社区  · 9 年前

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

    我想记录一个场景,我点击第二个产品的图标。 这样的场景如何避免含糊不清的ViewMatcherException?

    不幸的是,以下代码将无法工作-将找到三个R.id.tv_product_row_icon。。。

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

    如何指定要单击第二个图标?

    1 回复  |  直到 9 年前
        1
  •  5
  •   R. Zagórski Krishnraj Anadkat    9 年前

    不幸的是,您必须创建一个自定义 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());