Question

I want to unit test a swipe left/right action on the screen in Android but I haven't been able to find any documentation on it. Can anyone lend a hand? Can it even be done?

Was it helpful?

Solution

Generally the touch will perform an action and you will be testing the action, not the touch itself.

OTHER TIPS

I found your question trying to learn how to do the exact same thing for the exact same type of gesture. I was able to run pretty pure unit tests using the following approach. In other words unit test View.OnTouchListener.onTouch(View v, Event event) function.

Here is how I was able to "mock" the View and Event in order to run onTouch

import android.os.Looper;
import android.test.mock.MockContext;
import android.view.MotionEvent;
import android.view.ViewStub;
import junit.framework.TestCase;

public class SwipeDetectorTest extends TestCase {
    public void testOnTouch() throws Exception {
         class MyMockContext extends MockContext {
            public Looper getMainLooper() {
                return Looper.getMainLooper();
            }
        }
        MyMockContext context = new MyMockContext();
        View v = new ViewStub(context);
        int x = 0; int y = 0;

        // simulated down event
        MotionEvent event = 
            MotionEvent.obtain(1, 0, MotionEvent.ACTION_DOWN, x, y, 0);
        SwipeDetector swipeDetector = new SwipeDetector();
        assertFalse(swipeDetector.onTouch(v, event));

        x = 30; y = 0;
        event = 
           MotionEvent.obtain(1, 1, MotionEvent.ACTION_MOVE, x, y, 0);
        boolean action = swipeDetector.onTouch(v, event);
        assertTrue(action);

        boolean result = swipeDetector.getSwipeHorizontal()
            .equals(SwipeDetector.Action.LeftToRight);
        assertTrue(result);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top