How to check Viewpager item ids with Espresso?

2019-06-16 20:54发布

问题:

I have a Viewpager that's composed of copies of the same fragment view. You can swipe between them. I'm writing an Espresso test and trying to assert on ids of each page, but they are obviously ambiguous because there are multiple pages loaded and they all share the same ids. I don't want to change the view pager to load only 1 page at a time. In my application, it's inefficient to do so.

I've also thought of using tags and tag each view with a unique string, but then I'm modifying the source code only so that my test works. I don't like that. What is the correct way of checking content inside the page of a viewpager with Espresso?

回答1:

Assuming that only one of the pages is displayed at a time you can use swipeLeft/swipeRight to move to a page and then check that the right thing is displayed in that page.

There are some examples here.

e.g.

 onView(withId(R.id.pager))
   .perform(swipeLeft())
   .check(matches(hasDescendant(withText("Position #2"))));