在UI测试中自动化SFSafariViewController的任何方法吗?

时间:2015-09-24 13:44:31

标签: ios mobile-safari coded-ui-tests xctest xcode-ui-testing

有没有办法自动化SFSafariViewController?我喜欢Xcode 7 UI测试功能,但它似乎不支持SFSafariViewController自动化。我正在测试的一些UI流程需要一个Web浏览器,因此该应用程序使用SFSafariViewController使其比Web视图更安全。

2 个答案:

答案 0 :(得分:2)

如果它类似于启动扩展程序(目前已通过直接交互方式中断),请尝试在您要查找的元素点击屏幕:

点击启动扩展程序的操作表的示例:

func tapElementInActionSheetByPosition(element: XCUIElement!) {
    let tableSize = app.tables.elementBoundByIndex(0).frame.size
    let elementFrame = element.frame

    // get the frame of the cancel button, because it has a real origin point
    let CancelY = app.buttons["Cancel"].frame.origin.y

    // 8 is the standard apple margin between views
    let yCoordinate = CancelY - 8.0 - tableSize.height + elementFrame.midY

    // tap the button at its screen position since tapping a button in the extension picker directly is currently broken
    app.coordinateWithNormalizedOffset(CGVectorMake(elementFrame.midX / tableSize.width, yCoordinate / app.frame.size.height)).tap()
}

注意:您必须点击XCUIApplication查询图层。按位置点击元素不起作用。

答案 1 :(得分:0)

目前Xcode 9.3支持此功能,但由于annoying Xcode bug而无法正常运行。

在测试中,您可以打印app.webViews.buttons.debugDescriptionapp.webViews.textFields.debugDescription,并打印正确的信息,但在taptypeText之后您已经崩溃。

要解决此问题,您可以解析debugDescription,提取坐标并按坐标点按。对于文本字段,您可以通过“粘贴”菜单插入文本。

private func coordinate(forWebViewElement element: XCUIElement) -> XCUICoordinate? {
    // parse description to find its frame
    let descr = element.firstMatch.debugDescription
    guard let rangeOpen = descr.range(of: "{{", options: [.backwards]),
        let rangeClose = descr.range(of: "}}", options: [.backwards]) else {
            return nil
    }

    let frameStr = String(descr[rangeOpen.lowerBound..<rangeClose.upperBound])
    let rect = CGRectFromString(frameStr)

    // get the center of rect
    let center = CGVector(dx: rect.midX, dy: rect.midY)
    let coordinate = XCUIApplication().coordinate(withNormalizedOffset: .zero).withOffset(center)
    return coordinate
}

func tap(onWebViewElement element: XCUIElement) {
    // xcode has bug, so we cannot directly access webViews XCUIElements
    // as workaround we can check debugDesciption, find frame and tap by coordinate
    let coord = coordinate(forWebViewElement: element)
    coord?.tap()
}

关于此的文章:https://medium.com/@pilot34/work-with-sfsafariviewcontroller-or-wkwebview-in-xcode-ui-tests-8b14fd281a1f

完整代码在此处:https://gist.github.com/pilot34/09d692f74d4052670f3bae77dd745889