Xcode UI单元测试和权限警报

时间:2017-10-29 18:00:10

标签: ios swift xcode xctest xcode-ui-testing

我正在为我的应用程序进行UI单元测试,并且我正试图弄清楚如何自动让测试框架点击" OK"当系统提出要求访问联系人权限的警报时。

到目前为止,我已经查看了这四篇SO帖子,并尝试了各种建议,但我仍然无法使其工作:

XCTest app tests and permissions alerts

Xcode 7 UI Testing: how to dismiss a series of system alerts in code

Xcode UI Testing allow system alerts series

Xcode 7 UI Testing: Dismiss Push and Location alerts

这是我目前正在尝试的内容 - 但是,权限对话框仍未被自动接受;测试等待我点击" OK"在前进之前:     func testApp(){

    self.addUIInterruptionMonitor(withDescription: "MyDescription", handler: { (alert) -> Bool in
        let button = alert.buttons["OK"]
        if button.exists {
            button.tap()
            return true
        }
        return false
    })

    let app = XCUIApplication()
    app.launch()
    ...
    app.tap()
    ...
}

编辑: 以下是根据@ ad-johnson的建议做出的改变:

var app: XCUIApplication!

override func setUp() {
    super.setUp()

    continueAfterFailure = false
    app = XCUIApplication()

    addUIInterruptionMonitor(withDescription: "Contact Auth")
    { (alert) -> Bool in if alert.buttons["OK"].exists {
        alert.buttons["OK"].tap()
        }
        return true }

    app.launch()
}


func testScreenshots() {
    app.tap()
    ...
}

1 个答案:

答案 0 :(得分:2)

可能没有太多帮助,但这与我所拥有的相符(允许访问位置服务,所以我等待"允许"按钮。)唯一的区别是我的订单是1 )让app = 2)添加监视器3)启动应用程序。全部在setup()中。 app.tap位于func testApp()中。每次调用时,XCUIApplication()都会创建一个新的app实例:我想我会在第一个实例中尝试将它移到监视器之前。这是我的设置方法(忽略UITestHelper调用):

alert('date2 > date 4')
alert('date 2 > date 5')

和我的测试:

override func setUp() {
    super.setUp()

    continueAfterFailure = false
    app = XCUIApplication()

    // ensure app is currently authorised.  If the first install is to
    // happen then the settings won't exist yet but that's ok, the test
    // will handle the Location Services prompt and allow.
    UITestHelper.resetAuthorisation(setToInUse: true)

    addUIInterruptionMonitor(withDescription: "Location Services")
    { (alert) -> Bool in if alert.buttons["Allow"].exists {
        alert.buttons["Allow"].tap()
        }
        return true }

    app.launch()
}