I have a ViewPager
whith items containing only a picture and a button.
I can't successfully interact with the UI of an item (Page) because, except the displayed picture, there is nothing to differentiate (from UI point of view) all items of the ViewPager
.
I tried to select only one item with a position:
onData(is(instanceOf(ItemClass.class)))
.atPosition(0)
.onChildView(withId(R.id.button))
.perform(click());
causing:
NoMatchingViewException: No views in hierarchy found matching: is assignable from class: class android.widget.AdapterView
How to access and test items of a ViewPager
with Espresso ?
FirstVal,
ViewPager
is not anAdapterView
, it directly extends fromViewGroup
. So the methodonData()
cannot be used on aViewPager
.1. Solution
As it's a
ViewGroup
, each items are direct children of itsViewPager
. So the process is to reference the first view child using a custom matcher (like this onefirstChildOf()
) and playing withhasDescendant()
andisDescendantOfA()
to access the targeted view and perform an action on it.2. Solution (da best)
As the particularity of the
ViewPager
is to display each items (#1 solution's child views) that composed it, one by one (page-by-page style). So even if your items use the same layout with the same IDs, only one is displayed. So we can reference the targeted view by its Id and add the constraintsisDisplayed()
. It will match only one view, the one that is currently displayed.as simple as that.
And if you want another item, you may perform a
swipe()
on yourViewPager
to change the displayed item: