【问题标题】:In Espresso, how can I perform an action on all matching views without triggering an AmbiguousViewMatcherException?在 Espresso 中,如何在不触发 AmbiguousViewMatcherException 的情况下对所有匹配视图执行操作?
【发布时间】:2020-02-18 07:34:31
【问题描述】:

我正在使用 Espresso 在 Android 应用上运行自动化 UI 测试。我想对符合指定条件的 all 视图执行操作。 Espresso 确实使用allOf() 方法来查找匹配器匹配的所有视图。但是,如果有多个匹配项,onView(withText("some text")).perform(click()) 等命令将抛出 AmbiguousViewMatcherException

我确实有一种方法可以在有多个匹配项时获取第 n 个匹配视图。

    private static Matcher<View> getElementFromMatchAtPosition(final Matcher<View> matcher, final int position) {
        return new BaseMatcher<View>() {
            int counter = 0;

            @Override
            public boolean matches(final Object item) {
                if (matcher.matches(item)) {
                    if(counter == position) {
                        counter++;
                        return true;
                    }
                    counter++;
                }
                return false;
            }

            @Override
            public void describeTo(final Description description) {
                description.appendText("Element at hierarchy position " + position);
            }
        };
    }

当然,我可以使用这种方法循环浏览每个视图。但是有更优雅的解决方案吗?

如果我不知道有多少匹配视图怎么办?

【问题讨论】:

  • 您使用allOf()的情况如何?
  • 我才意识到我犯了一个错误。原来allOf() 表示所有匹配器,而不是所有与特定匹配器匹配的视图。哦!

标签: android android-espresso android-testing hamcrest


【解决方案1】:

听起来你可能错误地使用了allOf()

正如您在评论中指出的那样,allOf() 应该与匹配器一起使用。然后,您可以选择要选择的视图的所有独特方面,以逗号分隔。

这是一个例子:

onView(allOf(isDescendantOfA(withId(R.id.input)), withText("jeff@bob.com"))).check(matches(isDisplayed()));

【讨论】:

    猜你喜欢
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多