'RecyclerView test scroll to position

I'm trying to figure out RecyclerView tests with espresso, I'm trying to use the RecyclerViewActions.scrollTo to scroll to the specified item in the RecyclerView .

onView(withId(R.id.rv_container)).perform(
    RecyclerViewActions.scrollTo<ItemViewHolder>(
        hasDescendant(
            withText("Item: 40")
        )
    )
)

This is the error I get.

Error performing 'scroll RecyclerView to: holder with view: has descendant: with text: is "Item: 40"' on view 'with id is <com.example.endtoend:id/rv_container>'.
  • Windows animation scale
  • Transition animation scale
  • Animator duration scale

are all turned off

I'm also not sure why I have to cast ViewHolder here, Android dev examples don't cast ViewHolder.

Aaron's trick to get the RecyclerViews ViewHierachy.

androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'not is displayed on the screen to the user' doesn't match the selected view.
Expected: not is displayed on the screen to the user
     Got: "RecyclerView{id=2131231038, res-name=rv_container, visibility=VISIBLE, width=1440, height=1878, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@4b6b49e, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=532.0, child-count=12}"

enter image description here

ItemView XML

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rv_item_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="22sp"
    android:padding="8dp"/>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source