Android Espresso:将ListView中的行数保存到变量

时间:2018-08-07 14:39:25

标签: java android android-espresso

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

这怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用以下自定义匹配器来声明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())))