Espresso:如何测试 SwipeRefreshLayout?

Espresso: How to test SwipeRefreshLayout?

SwipeRefreshLayout 上向下滑动时,我的应用程序会重新加载数据。现在我尝试使用 Android 测试套件/浓缩咖啡进行测试,如下所示:

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 确实可以对其执行一些操作。

睡过头有时会有帮助。根本原因是待滑动视图只有 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)));