Android Espresso测试-测试RecyclerView项内是否可见视图

3
我有一个id为'rv_list'的RecyclerView。当点击任何RecyclerView项时,每个项内都有一个id为'star'的View变得可见。
我想使用Espresso来检查 - 在第一个RecyclerView项目上单击,检查视图R.id.star是否可见。
我的代码是 -
@Test
fun checkIfStarVisibleOnItemClick() {

  onView(withId(R.id.rv_list))
            .perform(RecyclerViewActions.actionOnItemAtPosition<RepositoriesAdapter.RepositoriesViewHolder>(0, click()))


   onView(withId(R.id.star))
            .check(matches(isDisplayed()))

 }

我遇到了这个错误 -

id/star'匹配了层次结构中的多个视图


1
https://dev59.com/MV0Z5IYBdhLWcg3wfgYR - dominicoder
1个回答

3

检查在“rv_list” RecyclerView 的第一个元素(位置0)中,具有id 'star'的项是否可见的代码应该是:

onView(withRecyclerView(R.id.rv_list)
    .atPositionOnView(0, R.id.star))
    .check(matches(isDisplayed()));

这些方法是espresso-contrib的一部分。 更新 现在我声明了这个方法:
fun nthChildOf(parentMatcher: Matcher<View?>, childPosition: Int): Matcher<View?>? {
    return object : TypeSafeMatcher<View>() {
        override fun describeTo(description: Description) {
            description.appendText("with $childPosition child view of type parentMatcher")
        }

        override fun matchesSafely(view: View): Boolean {
            if (view.parent !is ViewGroup) {
                return parentMatcher.matches(view.parent)
            }
            val group = view.parent as ViewGroup
            return parentMatcher.matches(view.parent) && group.getChildAt(childPosition) == view
         }
    }
}

然后这样使用它:

onView(allOf(
    withId(R.id.star),
        isDescendantOfA(
            nthChildOf(withId(R.id.rv_list), 0))
)).check(matches(isDisplayed()))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接