【问题标题】:iOS UI Test: how to get message of UIAlertControlleriOS UI 测试:如何获取 UIAlertController 的消息
【发布时间】:2015-11-12 09:13:35
【问题描述】:

我的应用有一个登录屏幕。如果用户在没有在用户名或密码字段中输入任何文本的情况下按下登录按钮,应用程序将显示带有错误消息的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 值,以便我可以对其进行断言?

【问题讨论】:

    标签: ios xcode7 xcode-ui-testing


    【解决方案1】:

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

    例如,假设您的警报如下所示:

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

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

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

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

    我的UI Testing Cheat Sheet and Examples 帖子和sample app 中提供了更多示例。

    【讨论】:

      【解决方案2】:

      除了上述我努力工作的答案之外,还有另一种方法。

      在您的 UItest 方法中创建一个错误的 Bool:

      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)
      

      我希望这对某人有所帮助。

      【讨论】:

      • 这个答案与原来的问题无关。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2017-09-29
        • 1970-01-01
        • 2018-06-23
        • 1970-01-01
        • 1970-01-01
        • 2019-11-03
        • 2014-09-22
        • 2011-03-27
        • 1970-01-01
        相关资源
        最近更新 更多