Android Espresso:将列表视图中的行数保存到变量

Android Espresso : Saving number of rows in listview to variable

我有一个正在测试的列表视图,需要计算列表中的行数。

如何做到这一点?

您可以像这样使用自定义匹配器断言 RecyclerListView 或 ListView 中的元素数量:

/**
 * Test if a RecyclerView contain the right amount of elements
 */
fun withListSize(size: Int): Matcher<View> {
    return object : TypeSafeMatcher<View>() {
        var listSize = 0
        public override fun matchesSafely(view: View): Boolean {
            if ((view !is RecyclerView)) throw IllegalStateException("You cannot assert withListSize in none RecyclerView View")
            listSize = view.adapter.itemCount
            return listSize == size
        }

        override fun describeTo(description: Description) {
            description.appendText("ListView should have $size items and currently $listSize items")
        }
    }
}

并像这样使用它:

         var listSize = 0
    Espresso.onView(ViewMatchers.withId(R.id.list))
            .check(ViewAssertions.matches(object : TypeSafeMatcher<View>() {
                public override fun matchesSafely(view: View): Boolean {
                    if ((view !is RecyclerView)) throw IllegalStateException("You cannot assert withListSize in none RecyclerView View")
                    listSize = view.adapter.itemCount
                    return listSize !=0
                }

                override fun describeTo(description: Description) {
                    description.appendText("ListView should not be empty")
                }
            }))

    // ADD TO the list

    Espresso.onView(ViewMatchers.withId(R.id.list))
            .check(ViewAssertions.matches(Matchers.allOf(withListSize(listSize + 1), ViewMatchers.isDisplayed())))