如何在 Xcode UI 测试脚本中执行点击和拖动?

How do I perform a tap and drag in Xcode UI Test scripts?

例如, 我有一个素描板应用程序,我想通过在上面绘图来测试它。我想指定一个 (x,y) 坐标并让它点击并拖动到另一个 (x,y) 坐标。

这在 Xcode UI 测试中可行吗?

Joe 提供了解决此问题的方法: 使用 objective C,我的代码看起来像这样:

XCUICoordinate *start = [element2 coordinateWithNormalizedOffset:CGVectorMake(0, 0)];
XCUICoordinate *finish = [element2 coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.5)];
[start pressForDuration:0 thenDragToCoordinate:finish];

其中 element2 是我必须执行拖动的 XCUI 元素。

您可以使用 XCUICoordinate 在 UI 测试中点击和拖动元素。这是通过 table 单元格坐标 how to pull to refresh 的示例。

let firstCell = app.staticTexts["Adrienne"]
let start = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 0))
let finish = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 6))
start.pressForDuration(0, thenDragToCoordinate: finish)

如果您没有可供参考的元素,您应该能够根据 XCUIApplication.

创建任意坐标
let app = XCUIApplication()
let fromCoordinate = app.coordinateWithNormalizedOffset(CGVector(dx: 0, dy: 10))
let toCoordinate = app.coordinateWithNormalizedOffset(CGVector(dx: 0, dy: 20))
fromCoordinate.pressForDuration(0, thenDragToCoordinate: toCoordinate)

UI 测试没有官方文档,但我已经抓取了 headers 并整理了一个 XCTest Reference 如果您对更多细节感兴趣。

或从 Swift 4 开始:

let view = window.staticTexts["FooBar"]
let start = view.coordinate(withNormalizedOffset: CGVector(dx: 10, dy: 20))
let finish = view.coordinate(withNormalizedOffset: CGVector(dx: 100, dy: 80))
start.press(forDuration: 0.01, thenDragTo: finish)