Swift 使用 Xcode UI 测试的异步事件处理

Swift ASYNC Event Handling With Xcode UI Test

我正在使用 swift 作为 Xcode UI 测试应用程序。我们被测试的应用程序有时会弹出一个 "Alert Box" 影响测试用例的正常工作流程。无法预测弹出窗口何时出现。它可能出现在测试用例 1 或测试用例编号 x。

我想关闭 "Alert Box" 并继续测试用例的其余部分。我如何使用 swift XCUI 测试框架处理类似的异步事件,而不影响测试用例的正常流程?

到目前为止我发现:

expectationForPredicate(exists, evaluatedWithObject: alertbox, handler: nil)
waitForExpectationsWithTimeout(300, handler: nil)

这是不可行的,原因有二。

  1. 无法预测超时
  2. 正在阻塞测试用例流

    func testTestCase1 {
        let expectation = expectationWithDescription("Alert Found! Dismissing")
        do {
            // ...
            // test steps
            // ...
            expectation.fulfill()
        }
        waitForExpectationsWithTimeout(300) {
            dimissAlert()
        }
    }
    

参考 1: https://www.bignerdranch.com/blog/asynchronous-testing-with-xcode-6/
参考 2: XCTest and asynchronous testing in Xcode 6
Ref3:https://adoptioncurve.net/archives/2015/10/testing-asynchronous-code-in-swift/

是否有通用的方法来处理整个套件中的异步事件?如何在另一个线程等待 "Alert Box" 出现事件时继续测试?

干杯!

Xcode 7.1 添加了 addUIInterruptionMonitorWithDescription,这似乎正是您要找的。此处的文档:https://developer.apple.com/reference/xctest/xctestcase/1496273-adduiinterruptionmonitorwithdesc?language=objc

Stephen 是对的,UI 中断监视器应该工作得很好。我建议将它添加到您的测试设置中,以便它运行您的所有测试。

class UITests: XCTestCase {
    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        addUIInterruptionMonitorWithDescription("Alert") { (alert) -> Bool in
            alert.buttons["OK"].tap()
            return true
        }
        app.launch()
    }

    func testFoo() {
        // example test
    }
}