浓缩咖啡:RecyclerViewActions.actionOnItemAtPosition 不起作用

Espresso: RecyclerViewActions.actionOnItemAtPosition doesn't work

我开始使用 Espresso 测试我的应用程序。 我的应用程序有一个 recyclerView。 以下代码有效:

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

但是下面的代码不起作用

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

RecyclerView data size = 66.

你能解释一下上面代码不起作用的原因吗? 谢谢并提前。

可能会出现一条错误消息,指出该元素在屏幕上不可见,这是因为您应该先滚动到该元素,然后再执行 click 操作。

我在 kotlin 中使用这个自定义 ViewAction 来执行滚动:

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()
    }
}

但是因为你有 RecyclerViewActions 你可以在执行点击之前使用 scrollToPosition():

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