I am trying to write an instrumentation test with Espresso for my Android app which uses a RecyclerView
. Here is the main layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
... and the item view layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
This means there are a couple of TextViews
on the screen which all have the label
id. I am trying to click a specific label. I tried to let Espresso test recorder generate the code:
onView(allOf(withId(R.id.grid), isDisplayed()))
.perform(actionOnItemAtPosition(5, click()));
I rather want to to something like:
// Not working
onView(allOf(withId(R.id.grid), isDisplayed()))
.perform(actionOnItem(withText("Foobar"), click()));
Readings
I read quite a bit about the topic but still cannot figure out how to test a RecyclerView
item based on its content not based on its position index.
- Advanced Android Espresso - Slide on RecyclerViewActions (Chiu-Ki Chan)
- RecyclerView and espresso, a complicated story (Patrick Bacon, Jul 18, 2015)
- Espresso – Testing RecyclerViews at Specific Positions (Romain Piel, April 15, 2016)