我正在为我的应用程序编写 Espresso 测试。对于一个测试,我必须单击 RecyclerView-Item 上的按钮。所述项目比屏幕大,因此当我滚动到该项目时,所需的按钮仍然没有显示(这是必需的,以便我可以单击它)。
我尝试滚动到 View
onView(withId(R.id.recycler_view)).perform(scrollTo<MyViewHolder>(hasDescendant(withId(R.id.target_button))))
但这只是滚动到包含该按钮的项目的顶部。由于该按钮位于该项目的最底部,并且该项目比屏幕大,因此当我尝试单击该按钮时,我得到
Action will not be performed because the target view does not match one or more of the following constraints:
at least 90 percent of the view's area is displayed to the user.
我也尝试过
onView(withId(R.id.recycler_view)).perform(actionOnItemAtPosition<MyViewHolder>(0, EspressoUtils.clickChildViewWithId(R.id.target_button)))
其中 EspressoUtils.clickChildViewWithId(id: Int)
是 this 接受的答案中描述的内容问题。这也产生了同样的错误。如何滚动到 RecyclerView-Item 中的特定子项?
最佳答案
当我单击屏幕两倍大的 RecyclerView 项目内的 View 时,以下解决方案适用于我。注意:我单击的 View 实际上位于屏幕之外,但由于它位于 View 层次结构中,因此可以单击它。
创建自定义 ViewAction:
private fun clickChildViewWithId(id: Int) = object : ViewAction {
override fun getConstraints() = null
override fun getDescription() = "click child view with id $id"
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<View>(id)
v.performClick()
}
}
用法:
onView(withId(R.id.recycler_view))
.perform(actionOnItemAtPosition<MyViewHolder>(0, clickChildViewWithId(R.id.target_button)))
关于android - 如何使用 espresso 滚动到 RecyclerView-Item 的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54705879/