Espresso:如何测试SwipeRefreshLayout?

时间:2015-11-03 17:55:27

标签: android testing android-espresso

我的应用在SwipeRefreshLayout上进行向下滑动时会重新加载数据。现在我尝试用Android Test Kit / Espresso测试这个:

onView(withId(R.id.my_refresh_layout)).perform(swipeDown());

不幸的是,

失败了
android.support.test.espresso.PerformException: Error performing 'fast swipe'
on view 'with id: my.app.package:id/my_refresh_layout'.
...
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.
Target view: "SwipeRefreshLayout{id=2131689751, res-name=my_refresh_layout, visibility=VISIBLE,
width=480, height=672, has-focus=false, has-focusable=true, has-window-focus=true,
is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, 
is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0,
child-count=2}"

当然,布局是可见的并且手动滑动有效,但我不确定我是否做错了什么?布局横跨整个屏幕,因此 真的可以让Espresso对其进行一些操作。

1 个答案:

答案 0 :(得分:41)

睡在它上面有时会有所帮助。根本原因在于,用户可以看到待刷卡的视图只有89%,而Espresso的刷卡操作内部需要90%。因此,解决方案是将滑动操作包装到另一个操作中并手动覆盖这些约束,如下所示:

public static ViewAction withCustomConstraints(final ViewAction action, final Matcher<View> constraints) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return constraints;
        }

        @Override
        public String getDescription() {
            return action.getDescription();
        }

        @Override
        public void perform(UiController uiController, View view) {
            action.perform(uiController, view);
        }
    };
}

然后可以这样调用:

onView(withId(R.id.my_refresh_layout))
    .perform(withCustomConstraints(swipeDown(), isDisplayingAtLeast(85));