使用Espresso测试ViewPager.如何对项目的按钮执行操作? [英] Testing ViewPager with Espresso. How perfom action to a button of an Item?

查看:178
本文介绍了使用Espresso测试ViewPager.如何对项目的按钮执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ViewPager项,其中仅包含图片和按钮.

I have a ViewPager whith items containing only a picture and a button.

我无法成功与项目(页面)的UI进行交互,因为除了显示的图片之外,没有任何东西可以区分(从UI角度来看)ViewPager的所有项目.

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());

原因:

NoMatchingViewException:找不到层次结构中符合以下条件的视图:可从类android.widget.AdapterView

NoMatchingViewException: No views in hierarchy found matching: is assignable from class: class android.widget.AdapterView

如何使用Espresso访问和测试ViewPager的项目?

How to access and test items of a ViewPager with Espresso ?

推荐答案

FirstVal,ViewPager不是AdapterView,它直接从ViewGroup扩展.因此,无法在ViewPager上使用onData() 方法.

FirstVal, ViewPager is not an AdapterView, it directly extends from ViewGroup. So the method onData() cannot be used on a ViewPager.

由于它是ViewGroup,所以每个项目都是其ViewPager的直接子代. 因此,该过程是使用自定义匹配器来引用第一个视图子项(例如,

As it's a ViewGroup, each items are direct children of its ViewPager. So the process is to reference the first view child using a custom matcher (like this onefirstChildOf()) and playing with hasDescendant() and isDescendantOfA() to access the targeted view and perform an action on it.

 onView(allOf(withId(R.id.button), isDescendantOfA(firstChildOf(withId(R.id.viewpager)))))
            .perform(click());


2.解决方案(最佳)

由于ViewPager的特殊性是要一一显示(逐页样式)显示组成它的每个项目(#1解决方案的子视图).因此,即使您的项目使用具有相同ID的相同布局,也只会显示一个.因此,我们可以通过其ID引用目标视图并添加约束 isDisplayed() .它只会匹配一个视图,即当前显示的视图.


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 constraints isDisplayed(). It will match only one view, the one that is currently displayed.

onView(allOf(withId(R.id.button), isDisplayed())).perform(click());

就这么简单.

如果您想要其他商品,则可以执行ViewPager上的="noreferrer"> swipe() 来更改显示的项目:

And if you want another item, you may perform a swipe() on your ViewPager to change the displayed item:

onView(withId(R.id.viewpager)).perform(swipeLeft());

这篇关于使用Espresso测试ViewPager.如何对项目的按钮执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆