ViewPager内の子Viewに対するテストはこれでできましたが、見えていないViewに対してRobolectricの感覚で操作を行おうとすると次のようなエラーが出てしまいます。
Caused by: java.lang.RuntimeException: 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.
仕方ないので今度はTabLayoutを操作してViewPagerを切り替えます。
public class MatcherUtil {
@NonNull
public static Matcher<View> TabMatcher(final Matcher<View> parentMatcher, final int index) {
return new TypeSafeMatcher<View>() {
@Override
protected boolean matchesSafely(View view) {
if (!(view.getParent() instanceof TabLayout)) {
return parentMatcher.matches(view.getParent());
}
TabLayout tabLayout = (TabLayout) view.getParent();
return parentMatcher.matches(view.getParent())
&& tabLayout.getTabCount() > index && tabLayout.getTabAt(index) != null;
}
@Override
public void describeTo(Description description) {
}
};
}
}
例:buttonというIDをもつViewがViewPager内2ページ目に存在するか
onView(TabMatcher(withId(R.id.tab), 1)).perform(click());
onView(allOf(withId(R.id.button), isDescendantOfA(ViewPagerMatcher(withId(R.id.pager), 1)))).check(matches(notNullValue()));