第二个活动上的单击按钮在视图上执行“单击”或“滚动到”时出错

单击Espresso测试中的按钮会出现问题。 假设我有两个活动“Activity1”和“Activity2”。 单击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 = Modify Parameter,input-type = 0,ime-target = false,has-links = 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,因为目标视图不匹配以下一个或多个约束:(视图具有有效可见性= VISIBLE并且是a的后代:(可从类中分配:class android .widget.ScrollView或可从类分配:class android.widget.Horizo​​ntalScrollView))目标视图:“按钮{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 = Modify参数,input-type = 0,ime-target = false,has- links = false}“at

解决方案是创建自定义的GeneralClickAction,其中包含您想要点击的视图可见性,然后Espresso的GeneralClickAction需要。 目前最低可见度值为90% – 请参见此处第60行的代码。将其设置为80%或更低。 只需复制整个类重命名它,并将提供给此方法的值更改为80 isDisplayingAtLeast(80) 。 然后创建使用自定义GeneralClickAction的单击操作:

  public static ViewAction customClick() { return actionWithAssertions( new CustomGeneralClickAction(Tap.SINGLE, GeneralLocation.VISIBLE_CENTER, Press.FINGER)); } 

但是,如果可能的话,我宁愿修复活动的布局,以避免为按钮可见性创建解决方法。

似乎您的视图带有ID R.id.btnMP在屏幕上不可见,因此您收到第一个错误。 您正尝试通过scrollTo()解决此问题,但您的视图不在ScrollView内部。 那你的活动是如何组织的? 如果您使用的是RecyclerView (例如),则应使用特殊版本的scrollTo – http://developer.android.com/reference/android/support/test/espresso/contrib/RecyclerViewActions.html等。 首先看一下托管视图的位置,然后将清楚如何滚动到它。