如何使用简单的触摸事件,例如 ACTION_DOWN
和 ACTION_MOVE
来测试视图?
如何使用简单的触摸事件,例如 ACTION_DOWN
和 ACTION_MOVE
来测试视图?
您可以轻松发送触摸事件。使用此视图操作:
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);
}
};
}
然后使用以下方式调用:
onView(withId(R.id.my_view)).perform(touchDownAndUp(x, y));
没有直接的方法可以像move(Gravity.LEFT, 40)
这样使用Espresso匹配器的方法。
对于一些目的,例如ACTION_DOWN
,您可以使用滑动方法,例如swipeDown()
请参阅Espresso.ViewActions参考文档:https://developer.android.com/reference/android/support/test/espresso/action/ViewActions.html
对于某些情况,您需要修改现有的方法,例如:Drag & Drop Espresso
还可以尝试将Espresso
与其他UI测试框架混合使用,例如已经具有一些很棒的匹配器和函数的Robotium
,例如touch()
方法,或者尝试另一个名为uiatomator
的Google框架。
请参阅:http://qathread.blogspot.com/2015/05/espresso-uiautomator-perfect-tandem.html
希望能对您有所帮助