Zappy.Mans
Zappy.Mans

Reputation: 672

Espresso: RecyclerViewActions.actionOnItemAtPosition doesn't work

I started testing my app with Espresso. My app have a recyclerView. Below code works:

int position = 0;
        onView(TestUtils.withIndex(withId(R.id.recyclerViewIcons),0)).perform(RecyclerViewActions.actionOnItemAtPosition(position,ViewActions.click()));

But below code doesn't work

int position = 40;
        onView(TestUtils.withIndex(withId(R.id.recyclerViewIcons),0)).perform(RecyclerViewActions.actionOnItemAtPosition(position,ViewActions.click()));

RecyclerView data size = 66.

Could you explain the reason above code doesn't work? Thanks and advance.

Upvotes: 1

Views: 2309

Answers (1)

jeprubio
jeprubio

Reputation: 18002

There is probably an error message saying that the element is not visible at screen and that's because you should first scroll until that element before performing the click action.

I use this custom ViewAction in kotlin to perform the scroll:

class ScrollToPositionAction(private val position: Int) : ViewAction {
    override fun getDescription(): String {
        return "Scroll RecyclerView to position: $position"
    }

    override fun getConstraints(): Matcher<View> {
        return allOf<View>(isAssignableFrom(RecyclerView::class.java), isDisplayed())
    }

    override fun perform(uiController: UiController?, view: View?) {
        val recyclerView = view as RecyclerView
        recyclerView.layoutManager?.smoothScrollToPosition(
            recyclerView, null, position
        )
        Thread.sleep(500)
        uiController?.loopMainThreadUntilIdle()
    }
}

But since you have the RecyclerViewActions you could use scrollToPosition() before performing the click:

int position = 40;
onView(TestUtils.withIndex(withId(R.id.recyclerViewIcons),0))
    .perform(
        RecyclerViewActions.scrollToPosition(position),
        RecyclerViewActions.actionOnItemAtPosition(position, ViewActions.click())
    );

Upvotes: 1

Related Questions