单击Espresso测试中的按钮会出现问题。让我们说我有两个活动"活动1"和"活动2"。单击Activity1中的对话框确定按钮启动Activity2,其中无法单击Activity2中的按钮。
// The current activity in testing
// .....
onView(withText(R.string.dialog_btn_ok)).perform(click()); // go to the second activity
// The button on the second activity
onView(withId(R.id.btnMP)).check(matches(isDisplayed())); // this is ok
onView(withId(R.id.btnMP)).perform(click()); // got error here
android.support.test.espresso.PerformException:执行错误 '单击'在视图' id:..........
引起:java.lang.RuntimeException:不会执行操作 因为目标视图与以下一个或多个不匹配 约束:显示至少90%的视图区域 用户。目标视图:"按钮{id = 2131296390,res-name = btnMP, visibility = VISIBLE,width = 652,height = 160,has-focus = false, has-focusable = true,has-window-focus = true,is-clickable = true, is-enabled = true,is-focused = false,is-focusable = true, is-layout-requested = false,is-selected = false, root-is-layout-requested = false,has-input-connection = false,x = 20.0, y = -16.0,text =修改参数,input-type = 0,ime-target = false, 具有链接= FALSE}"
当我使用perform(scrollTo())
更改此内容时,会显示不同的错误。
// The button on the second activity
onView(withId(R.id.btnMP)).check(matches(isDisplayed())); // this is ok
onView(withId(R.id.btnMP)).perform(scrollTo(), click()); // got error here
android.support.test.espresso.PerformException:执行错误 '滚动到'在视图'与id ....
引起:java.lang.RuntimeException:因为不会执行Action 目标视图与以下一个或多个约束不匹配: (视图有效可见性=可见并且是a的后代:(是 可从类中分配:类android.widget.ScrollView或是 可从类分配:class android.widget.HorizontalScrollView)) 目标视图:"按钮{id = 2131296390,res-name = btnMP, visibility = VISIBLE,width = 652,height = 160,has-focus = false, has-focusable = true,has-window-focus = true,is-clickable = true, is-enabled = true,is-focused = false,is-focusable = true, is-layout-requested = false,is-selected = false, root-is-layout-requested = false,has-input-connection = false,x = 20.0, y = -16.0,text =修改参数,input-type = 0,ime-target = false, 具有链接= FALSE}"在
答案 0 :(得分:3)
解决方案是创建自定义GeneralClickAction,其中包含您希望点击的视图可见性低于Espresso的GeneralClickAction要求。目前,最低可见性值为90% - 请参阅代码here第60行。将其设置为80%或更低。只需复制整个类重命名它,并将提供给此方法的值更改为80 isDisplayingAtLeast(80)
。然后创建使用自定义GeneralClickAction的单击操作:
public static ViewAction customClick() {
return actionWithAssertions(
new CustomGeneralClickAction(Tap.SINGLE, GeneralLocation.VISIBLE_CENTER, Press.FINGER));
}
但我宁愿修复活动的布局,以避免为按钮可见性创建变通方法。
答案 1 :(得分:1)
似乎您的ID为R.id.btnMP
的视图在屏幕上不可见,因此您收到第一个错误。您试图通过scrollTo()
解决此问题,但您的视图不在ScrollView中。那么你的活动是如何组织的?如果您使用RecyclerView
(例如),则应使用特殊版本的scrollTo - http://developer.android.com/reference/android/support/test/espresso/contrib/RecyclerViewActions.html,依此类推。首先看一下托管视图的位置,然后清楚如何滚动到它。