Search code examples
androidandroid-espressouitest

Tapping the first matching text on a recycler view Android espresso Testing


I am trying to tap on the first element of a matching text in my app. However at the moment i am receiving an error telling me there are multiple matches due to my current line of code. onView(allOf(withId(R.id.offerSummaryLayout))).perform(RecyclerViewActions.actionOnItem(Matchers.allOf(hasDescendant(withText("Online sale"))), click()));

How can I change this so it clicks on the first matching element? Thanks in advance


Solution

  • If you have multiple matches and you only care about the first one, you can create a custom matcher. This one here should work just fine.

    Then you can do things like that (I simplified your code a bit - you don't need Matchers.allOf if you have only a single condition):

    onView(withId(R.id.offerSummaryLayout)).perform(RecyclerViewActions
            .actionOnItem(first(hasDescendant(withText("Online sale"))), click()));