Geob-o-matic
Geob-o-matic

Reputation: 6079

Robotium equivalent of drag() in Espresso?

I'm using Espresso to test my application and I need to test a drag n drop behavior in a RecyclerView. Unfortunately I can't see any drag() action in Espresso, am I missing something?

Upvotes: 1

Views: 1089

Answers (1)

piotrek1543
piotrek1543

Reputation: 19351

I haven't found any Espresso dragging options. Only swipeUp(), swipeDown(), swipeLwft(),swipeRight(), which might be not useful in that case.

Moreover, on Google Groups there is an issue with no answer: https://groups.google.com/forum/#!msg/android-test-kit-discuss/X3TDJBUT4Ho/OJAOkTOoxGcJ

Although, there is also Espresso MotionEvents class with sendMovement() method, but I haven't tried it.

Use the code below:

 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();
    }

Also read about TouchUtils(already deprecated from API 24): https://developer.android.com/reference/android/test/TouchUtils.html

Hope it will help

Upvotes: 2

Related Questions