How to assert inside a RecyclerView in Espresso?

后端 未结 11 1833
故里飘歌
故里飘歌 2020-12-02 06:38

I am using espresso-contrib to perform actions on a RecyclerView, and it works as it should, ex:

onView(withId(R.id.recycler_view))
.perform(Rec         


        
11条回答
  •  孤街浪徒
    2020-12-02 07:01

    I combined a few answers above into a reusable method for testing other recycler views as the project grows. Leaving the code here in the event it helps anyone else out...

    Declare a function that may be called on a RecyclerView Resource ID:

    fun Int.shouldHaveTextAtPosition(text:String, position: Int) {
        onView(withId(this))
            .perform(scrollToPosition(position))
            .check(matches(atPosition(position, hasDescendant(withText(text)))))
    }
    

    Then call it on your recycler view to check the text displayed of multiple adapter items in the list at a given position by doing:

    with(R.id.recycler_view_id) {
        shouldHaveTextAtPosition("Some Text at position 0", 0)
        shouldHaveTextAtPosition("Some Text at position 1", 1)
        shouldHaveTextAtPosition("Some Text at position 2", 2)
        shouldHaveTextAtPosition("Some Text at position 3", 3)
    }
    

提交回复
热议问题