简体   繁体   中英

Android espresso match view duplicated inside RecyclerView

I have a recycler view with the following layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/color_primary"/>

</RelativeLayout>

I have a problem because during a test I have a moment where the recycler view show two views with the same text and I need to check if one of them is visible.

The code to match the view is the following:

onView(withId(R.id.title)).check(matches(withText("Test")));

And espresso is failing because it is finding more than one view that matchs the matcher criteria.

How can I match the specific view that I need?

One possible solution is to set a different tag in each row and use this tag to match with espresso.

Let's say the data that is being shown is persisted in the database. You can use the model id as the tag, with this you will have each row in the recycler view with a unique constraint that you can use in the matcher.

The code would be something like this:

onView(allOf(
            withId(R.id.title),
            allOf(
                isDescendantOfA(withTagValue(is((Object)model.getId())))),
                withText(model.getTitle())))
       .check(matches(isDisplayed()))

Since you need to use the text inside the matcher, you can check if the view is visible to add a clause to your test.

You can read an article explaining this here: https://medium.com/tech-track/validating-views-by-tag-with-espresso-50d3f47b14a7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM