Search code examples
android-listviewpositionrowandroid-espressoui-testing

How can I click on a View in ListView specific row position


I have a ListView:

enter image description here

And I want to click on a specific button within a ListView.

If I want to select with the onData selector:

onData(withId(R.id.button))
                .inAdapterView(withId(R.id.list_view))
                .atPosition(1)
                .perform(click());

And I get this error:

android.support.test.espresso.PerformException: Error performing 'load adapter data' on view 'with id: com.example.application:id/list_view'.
...

How can I solve this?


Solution

  • onData() requires an object matcher for the item that you are interested in. If you don't care about the data in the adapter you can use Matchers.anything() to effectively match all objects in the adapter. Alternatively you can create a data matcher (depending on data that is stored in the adapter) for your item and pass it in for a more deterministic test.

    As for the button - what you are looking for is an onChildsView() method, which allows to pass a viewmatcher for the descendant of the listitem, that was matched in the onData().atPosition()

    And as a result your test will look something like this:

        onData(anything()).inAdapterView(withId(R.id.list_view))
                .atPosition(1)
                .onChildView(withId(R.id.button))
                .perform(click());