【发布时间】:2021-04-07 14:45:37
【问题描述】:
我很难弄清楚如何使用 espresso 测试某个图像是否显示在 recyclerview 的某个位置上。我有一个人员列表,当其中一个被选中时,我会在 recyclerview 中围绕他的图像显示一个选定的指示器。所以我想检查一下,例如,位置 0 是否显示了这个指示器。我正在尝试的是:
fun test(position: Int, @DrawableRes res: Int): ViewInteraction {
return onView(withId(recyclerViewId)).check(matches(hasItemAtPosition(position, hasBackground(res))))
}
private fun hasItemAtPosition(position: Int, matcher: Matcher<View>): Matcher<View> {
return object : BoundedMatcher<View, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description?) {
description?.appendText("has item at position $position : ")
matcher.describeTo(description)
}
override fun matchesSafely(recyclerView: RecyclerView): Boolean {
val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
?: return false
return matcher.matches(viewHolder.itemView)
}
}
}
如果我使用 withText 而不是 withBackground 并匹配项目的文本,则此代码可以正常工作。
我得到的错误如下所示:
androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'has item at position 0 : has background with drawable ID: 2131231310' doesn't match the selected view.
Expected: has item at position 0 : has background with drawable ID: 2131231310
我对意式浓缩咖啡和一般测试有点陌生,所以希望有人有任何建议。
更新:
测试方法在一个自定义类中,我看起来像这样:
class RecyclerViewWait(@IdRes val recyclerViewId: Int) {
test()
hasItemAtPosition()
}
所以这两种方法也在那里(上面的那些)
我从另一个班级给他们打电话,像这样:
override fun doesPositionContainImageInList(position: Int, imageRes: Int): ViewInteraction {
return RecyclerViewWait(R.id.recyclerViewTest).checkBackground(position, imageRes)
作为回报从我的机器人类中调用,如下所示:
fun isImageShown(): Boolean {
return viewFinder.doesPositionContainImageInList(
0,
R.drawable.ic_selected_avatar
).isDisplayed()
}
我希望这是有道理的。
【问题讨论】:
标签: android kotlin testing android-espresso