How can I test a view with simple touch events such as ACTION_DOWN
and ACTION_MOVE
?

- 2,253
- 2
- 25
- 49
2 Answers
You can easily send touch events. Use this view action:
public static ViewAction touchDownAndUp(final float x, final float y) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return "Send touch events.";
}
@Override
public void perform(UiController uiController, final View view) {
// Get view absolute position
int[] location = new int[2];
view.getLocationOnScreen(location);
// Offset coordinates by view position
float[] coordinates = new float[] { x + location[0], y + location[1] };
float[] precision = new float[] { 1f, 1f };
// Send down event, pause, and send up
MotionEvent down = MotionEvents.sendDown(uiController, coordinates, precision).down;
uiController.loopMainThreadForAtLeast(200);
MotionEvents.sendUp(uiController, down, coordinates);
}
};
}
And invoke it with:
onView(withId(R.id.my_view)).perform(touchDownAndUp(x, y));

- 14,917
- 2
- 69
- 74
-
1This solution looks good, but how do you get x and y of a certain view? – AndroidRuntimeException Sep 15 '21 at 23:28
There's no direct way no Espresso matchers like move(Gravity.LEFT, 40)
methods.
For some purposes like ACTION_DOWN
you can use swiping methods like swipeDown()
Check Espresso.ViewActions Reference: https://developer.android.com/reference/android/support/test/espresso/action/ViewActions.html
For some you would need to modify existing methods like here: Drag & Drop Espresso
Also try to mix Espresso
with other UI instrumentation frameworks like Robotium
which already has some great matchers and function which Espresso doesn't have like touch()
method or try another Google's framework called uiatomator
.
Check: http://qathread.blogspot.com/2015/05/espresso-uiautomator-perfect-tandem.html
Hope it will help

- 1
- 1

- 19,130
- 7
- 81
- 94