Robotium相当于Espresso中的drag()?

时间:2016-09-14 07:19:08

标签: android android-studio android-testing android-espresso robotium

我使用Espresso测试我的应用程序,我需要在RecyclerView中测试拖放行为。不幸的是,我在Espresso中看不到任何拖动()动作,我错过了什么?

1 个答案:

答案 0 :(得分:1)

我没有找到任何Espresso拖动选项。只有swipeUp()swipeDown()swipeLwft()swipeRight(),在这种情况下可能没用。

此外,在Google网上论坛中存在无法解答的问题:https://groups.google.com/forum/#!msg/android-test-kit-discuss/X3TDJBUT4Ho/OJAOkTOoxGcJ

虽然还有Espresso MotionEventssendMovement()方法,但我还没有尝试过。

使用以下代码:

 public static void drag(Instrumentation inst, float fromX, float toX, float fromY,
                            float toY, int stepCount) {
        long downTime = SystemClock.uptimeMillis();
        long eventTime = SystemClock.uptimeMillis();

        float y = fromY;
        float x = fromX;

        float yStep = (toY - fromY) / stepCount;
        float xStep = (toX - fromX) / stepCount;

        MotionEvent event = MotionEvent.obtain(downTime, eventTime,
                MotionEvent.ACTION_DOWN, x, y, 0);
        inst.sendPointerSync(event);
        for (int i = 0; i < stepCount; ++i) {
            y += yStep;
            x += xStep;
            eventTime = SystemClock.uptimeMillis();
            event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0);
            inst.sendPointerSync(event);
        }

        eventTime = SystemClock.uptimeMillis();
        event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);
        inst.sendPointerSync(event);
        inst.waitForIdleSync();
    }

另请阅读TouchUtils(已从API 24弃用):https://developer.android.com/reference/android/test/TouchUtils.html

希望它会有所帮助