首页 > 解决方案 > 使用 Java mousePress、mouseMove 和 mouseRelease 进行单击和拖动

问题描述

我正在为 openLayers Web 应用程序(类似于 Google 地图)编写自动测试,试图让它像任何用户通常那样单击并拖动以平移地图。经过多次尝试和研究,我仍然无法让它自动平移。这是使用 Chrome 驱动程序。

我的代码似乎是正确的,因为我尝试开始测试,然后快速切换到一个充满文本的记事本窗口,瞧,文本被突出显示。

Robot robot = new Robot()
robot.mouseMove(501,501) // starting cursor position, somewhere near the middle of the map
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK)
// robot.delay(1000) // tried this but it made no difference
Thread.sleep(1000)
robot.mouseMove(400,400) // another position, still within the map's frame
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK)

预期结果:地图平移

实际结果:光标跳转位置但地图不动

没有错误信息

更新:如果我在测试运行时将鼠标光标稍微移动到地图上,则平移会按预期进行。

标签: javagroovyautomated-testsopenlayersmousepress

解决方案


与此同时,我可能已经找到了自己问题的答案。

对于我的地图应用程序来说,光标的速度可能太快了,所以我将 mouseMove() 方法放在一个循环中,每次迭代时,x 和 y 位置都会增加或减少一个像素。最后还添加了一个robot.delay(5)。结果看起来像一个平滑的鼠标移动。这是一个片段:

int pixX = 499
int pixY = 499

robot.mouseMove(500, 500) // Setting cursor starting position
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK)
robot.delay(500)

    while(pixX > 450 && pixY > 450) {
        robot.mouseMove(pixX, pixY)
        pixX--
        pixY--
        robot.delay(5)
    }
robot.delay(100) // Short delay at the end before releasing mouse button
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK)

推荐阅读