如何关注浓缩咖啡中的页面元素?

时间:2017-02-28 11:28:07

标签: android android-espresso hamcrest

我正在尝试使用以下方法检查/取消选中我的espresso测试中的复选框:

 termsAndConditionsCheckbox.check(matches(isChecked()));
 termsAndConditionsCheckbox.perform(scrollTo()).perform(click());
 termsAndConditionsCheckbox.check(matches(isNotChecked()));

但是得到错误:

Error performing 'scroll to' on view
Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
          (view has effective visibility=VISIBLE and is descendant of a: (is assignable from class: class android.widget.ScrollView or is assignable from class: class android.widget.HorizontalScrollView))
          Target view: "AppCompatCheckBox{id=2131689839, res-name=tnc_checkbox, visibility=VISIBLE, width=96, height=96, 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-conn

尝试删除scrollTo并仅使用click()。但仍然无法执行点击。

2 个答案:

答案 0 :(得分:1)

您收到的错误消息指出,您的CheckBox必须同时为VISIBLE,且ScrollViewHorizontalScrollView为子女。您的CheckBox确实是VISIBLE,但不是ScrollView的孩子。因此,如果您有如下布局:

<LinearLayout ...>
    <TextView android:id="@+id/lbl_license_text" ... />
    <CheckBox android:id="@+id/chk_accept" ... />
</LinearLayout>

您需要将其包装在ScrollView内,以便视图可以在小屏幕设备上滚动:

<ScrollView ...>
    <LinearLayout ...>
        <TextView android:id="@+id/lbl_license_text" ... />
        <CheckBox android:id="@+id/chk_accept" ... />
    </LinearLayout>
</ScrollView>

(显然将...的实例替换为该元素的android:属性)

这将允许Espresso在运行测试时向下滚动到CheckBox

答案 1 :(得分:0)

我能够通过实现自定义ViewAction函数来解决这个问题(在stackoverflow的一个答案中看到它)

 public static ViewAction setChecked(final boolean checked) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return new Matcher<View>() {
                @Override
                public boolean matches(Object item) {
                    return isA(Checkable.class).matches(item);
                }

                @Override
                public void describeMismatch(Object item, Description mismatchDescription) {}

                @Override
                public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {}

                @Override
                public void describeTo(Description description) {}
            };
        }

        @Override
        public String getDescription() {
            return null;
        }

        @Override
        public void perform(UiController uiController, View view) {
            Checkable checkableView = (Checkable) view;
            checkableView.setChecked(checked);
        }
    };
}

然后致电:

termsAndConditionsCheckbox.perform(Helper.setChecked(false));

取消选中并传递true以选中复选框。