如何等待位置警报(系统警报)显示?

时间:2016-12-23 01:16:20

标签: xcode8 xctest ios-ui-automation

我想出了如何解除系统警报,但我无法等待它显示,因为应用程序没有看到系统警报。我尝试使用app.debugDescription和app.alerts.count进行调试,但没有运气。

2 个答案:

答案 0 :(得分:7)

你应该使用addUIInterruptionMonitor作为@Oletha写的。

这里棘手的部分是系统警报按钮不使用辅助功能标识符,因此您必须搜索文本以点击它们。此文本被翻译为您运行模拟器/设备的语言,如果您想要在英语旁边运行多种语言的测试,这可能很难。

您可以使用AutoMate framework来简化此操作。这里有一个如何使用AutoMate处理系统警报的示例:

func locationWhenInUse() {
    let token = addUIInterruptionMonitor(withDescription: "Location") { (alert) -> Bool in
        guard let locationAlert = LocationWhenInUseAlert(element: alert) else {
            XCTFail("Cannot create LocationWhenInUseAlert object")
            return false
        }

        locationAlert.allowElement.tap()
        return true
    }

    // Interruption won't happen without some kind of action.
    app.tap()
    // Wait for given element to appear
    wait(forVisibilityOf: locationPage.requestLabel)
    removeUIInterruptionMonitor(token)
}

在上面的示例中,locationAlert.allowElement.tap()是可能的,因为AutoMate可以处理iOS模拟器支持的任何语言。

有关如何使用AutoMate处理系统警报的更多示例,请查看:PermissionsTests.swift

答案 1 :(得分:0)

使用addUIInterruptionMonitor:withDescription:handler:注册中断监视器。要“等待”出现系统警报,请使用处理程序在处理变量时设置变量,并在需要等待警报时与应用程序执行良性交互。

您必须在等待时继续与应用程序交互,因为交互是触发中断监视器的内容。

class MyTests: XCTestCase {

    let app = XCUIApplication()

    func testLocationAlertAppears() {
        var hasDismissedLocationAlert = false
        let monitor = addUIInterruptionMonitor(withDescription: "LocationPermissions") { (alert) in
            // Check this alert is the location alert
            let location = NSPredicate(format: "label CONTAINS 'Location'")
            if alert.staticTexts.element(matching: location).exists {
                // Dismiss the alert
                alert.buttons["Allow"].tap()
                hasDismissedLocationAlert = true
                return true
            }
            return false
        }

        // Wait for location alert to be dismissed
        var i = 0
        while !hasDismissedLocationAlert && i < 20 {
            // Do some benign interaction
            app.tap()
            i += 1
        }

        // Clean up
        removeUIInterruptionMonitor(monitor)

        // Check location alert was dismissed
        XCTAssertTrue(hasDismissedLocationAlert)
    }
}