Espresso – check if the TextView exists in the ListView

Issue

I want to check displaying of Save €XX in the list. Save €XX is a TextView that can be VISIBLE or INVISIBLE. I use JUnit 4 and Espresso 2.2.1.

I tried to check it like this:

onView(withText(startsWith("Save"))).check(matches(isDisplayed()));

but always get an error:

android.support.test.espresso.AmbiguousViewMatcherException: 'with text: a string starting with "Save"' matches multiple views in the hierarchy.

Is there a way to if the TextView exists in the ListView with Espresso?

UPDATE

I also tried to use onData:

onData(hasToString(startsWith("Save")))
                .inAdapterView(withId(R.id.suggestion_list_view)).atPosition(0)
                .check(matches(isDisplayed()));

but it seems that onData works with data layer but not the view layer. Therefore, I receive the error:

java.lang.RuntimeException: No data found matching: with toString() a string starting with "Save" contained values: <[Data: ...]>

enter image description here

Solution

After several tries, I found the way.

In this case, we should use a combined approach and work with both data and view layers. We access the ListView by ID and choose the first item. Then check it for the ‘Save’ text.

onData(anything())
                .inAdapterView(withId(R.id.list_view))
                .atPosition(0)
                .onChildView(withId(R.id.suggestion_saving))
                .check(matches(withText(startsWith("Save"))));

Works like a charm. Enjoy!

Answered By – Val

Leave a Comment