我有一个包含Fragment
的RecyclerView
。但由于我在这个Fragment
中有很多元素,我想向上扫描列表以查看并检查此Fragment
中的所有元素。
早些时候这种方法对我有所帮助,但现在由于某种原因它不起作用:
Espresso.onView(ViewMatchers.withId(R.id.recyclerView)).perform(ViewActions.swipeUp())
我的项目中有很多RecyclerView
s与id
相同:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
在我的测试中我写了这样的东西:
onView(allOf( withId(R.id.recyclerView), isDisplayed()))
onView(withId(R.id.recyclerView)).perform(swipeUp())
但仅在第二行捕获错误。
android.support.test.espresso.AmbiguousViewMatcherException:'with id:com.fentury.android:id/recyclerView'匹配层次结构中的多个视图。问题视图在下方标有“**** MATCHES ****”。
您在视图层次结构中有id R.id.recyclerView
的多个视图,因此espresso缺少执行正确匹配。使那些id
s的RecyclerView
s独一无二。
onView(allOf(withId(R.id.recyclerView), isDisplayed()))
onView(withId(R.id.recyclerView)).perform(swipeUp())
但仅在第二行捕获错误。
然后以这种方式执行匹配:
onView(allOf(withId(R.id.recyclerView), isDisplayed())).perform(swipeUp())
解:
onView(allOf(withId(R.id.recyclerview), isDisplayed())).perform(swipeUp());
您应该使用数据进行回收站视图,您可以使用回收站视图的id以及它所拥有的数据类型断言。这应该有助于假设不同的回收者视图不具有相同类型的数据,但是更好的做法是根据其使用的内容对不同的视图使用不同的ID。
您可能还想使用perform(ViewActions.scrollTo())
我在ViewPager中的两个片段中遇到了多个RecyclerViews的相同问题。两个片段使用相同的布局文件,仅包含带有id = @id / list的RecyclerView。
由于没有匹配的父级,我使用自定义ViewMatcher来匹配Adapter-Class的列表:(Kotlin)
fun hasAdapterOfType(T: Class<out RecyclerView.Adapter<out RecyclerView.ViewHolder>>): BoundedMatcher<View, RecyclerView> {
return object : BoundedMatcher<View, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description) {
description.appendText("RecycleView adapter class matches " + T.name)
}
override fun matchesSafely(view: RecyclerView): Boolean {
return (view.adapter.javaClass.name == T.name)
}
}
}
用法如下:
onView(allOf(withId(list), hasAdapterOfType(AccessAttemptListAdapter::class.java))).check(blabla)