iOS UI 测试:如何获取 UIAlertController 的消息

iOS UI Test: how to get message of UIAlertController

我的应用程序有一个登录屏幕。如果用户在没有在用户名或密码字段中输入任何文本的情况下按下登录按钮,应用程序将显示 UIAlertController 和错误消息。

我正在尝试在 UI 测试中模拟此逻辑,并想断言 UIAlertController 正在显示正确的消息。但是,我找不到 UI 测试访问警报消息 属性 的方法。这是测试记录器生成的代码:

func testLoginWithoutPasswort() {
    let app = XCUIApplication()
    let emailTextField = app.textFields["email"]
    emailTextField.tap()
    emailTextField.typeText("xxx@gmail.com")
    app.buttons["Login"].tap()
    app.alerts["Error"].collectionViews.buttons["OK"].tap()
}

有什么方法可以提取警报消息的 String 值,以便我可以对其进行断言?

我认为是:alert.elements()[2].name()onAlert 回调函数中添加 alert.logElementTree() 以查看 AlertView 元素。它可能是零,也许只显示标题。

您无法直接测试警报的消息。但是,您可以测试警报 是否包含 您的错误消息的副本(完全)。

例如,假设您的提醒如下所示:

要断言警报包含 "Final Score" 消息,请使用:

XCTAssert(app.alerts.element.staticTexts["Final Score: 27 - 25"].exists)

您也可以直接测试警报的标题

XCTAssertEqual(app.alerts.element.label, "You won!")

More examples available in my UI Testing Cheat Sheet and Examples post and sample app.

除了上面的答案,我努力开始工作,还有另一种方法。

在您的 UItest 方法中创建一个布尔值,它是错误的:

var alertPressed = false

然后添加一个 UIInterruptionMonitor 并在其闭包中将 bool 设置为 true:

addUIInterruptionMonitor(withDescription: "System Dialog") {
        (alert) -> Bool in
        alert.buttons["Allow"].tap()
        alertPressed = true
        return true
    }

然后再次与应用程序交互,并断言 Bool 为真

app.tap()
XCTAssert(alertPressed)

希望对大家有所帮助。