google-developer-training / android-basics-kotlin-affirmations-app-solution

Apache License 2.0
58 stars 49 forks source link

Android Basics: Test RecyclerView - scrollTo() #164

Closed ramezs closed 10 months ago

ramezs commented 2 years ago

URL of codelab https://developer.android.com/codelabs/android-basics-kotlin-affirmations-test-lists-and-adapters?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-kotlin-unit-2-pathway-3%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fandroid-basics-kotlin-affirmations-test-lists-and-adapters#6

In which task and step of the codelab can this issue be found? Step 2.

Describe the problem The following line always fails when running the test: RecyclerViewActions.scrollTo<RecyclerView.ViewHolder>(withText(R.string.affirmation10)) To fix it we should add HasDescendantMatcher as following: onView(withId(R.id.recycler_view)).perform(RecyclerViewActions.scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText(R.string.affirmation10))))

This is because RecyclerViewActions.scrollTo takes itemViewMatcher as per the API documentation:

Params: itemViewMatcher – a Matcher that matches an item view in RecyclerView

Without using hasDescendant the matcher will match the TextView instead of the itemView container which is required by scrollTo() function.

Steps to reproduce? 1- Run the UI Test AffirmationsListTests.scroll_to_item() 2- You will get the error: Error performing 'scroll RecyclerView to: holder with view: an instance of android.widget.TextView and view.getText() equals string from resource id: <2131623964>'

Versions 'androidx.test.espresso:espresso-contrib:3.4.0'

Natzely commented 1 year ago

Thank you @ramezs! I was getting this exact error. The previous test of .scrollToPosition was working fine, but when the test was updated to use the .scrollTo I started getting the error. Adding hasDescendant solved my issue! Hopefully the Android Team will update this tutorial.

adrian-best commented 1 year ago

I was also getting the same error, and for some reason the solution code in the repo has the hard coded '9' value, so it looks like this was overlooked anyways.