【问题标题】:Swift UI Testing Access string in the TextFieldSwift UI 测试 TextField 中的访问字符串
【发布时间】:2016-02-20 20:58:55
【问题描述】:

我正在使用 Xcode 中集成的 UI Test Case 类和 XCTest 来测试应用程序 UI。我想测试这样的东西:

app = XCUIApplication()
let textField = app.textFields["Apple"]
textField.typeText("text_user_typed_in")
XCTAssertEqual(textField.text, "text_user_typed_in")

我已经尝试过textField.value as! String 方法;这是行不通的。 我也尝试过使用expectationForPredicate() 的新异步方法,它会导致超时。

知道如何使用 UI 测试来执行此操作或进行此类验证,而我只能编写黑盒测试吗?

【问题讨论】:

  • Thx @Charles A. 指出问题是 textField 不存在。我很困惑,因为我调用了 typeText 方法,我可以看到文本正在输入到 textField 中。

标签: ios swift xcode-ui-testing


【解决方案1】:

我使用这个代码,它工作正常:

textField.typeText("value")
XCTAssertEqual(textField.value as! String, "value")

如果您正在做类似的事情并且它不起作用,我会检查以确保您的 textField 元素确实存在:

XCTAssertTrue(textField.exists, "Text field doesn't exist")
textField.typeText("value")
XCTAssertEqual(textField.value as! String, "value", "Text field value is not correct")

【讨论】:

  • 是的,你是对的。文本字段不存在。但我不明白这一点:我在 textField 上调用 typeText ,我可以看到文本正在输入到 textField 中。
  • 我应该使用异步方法吗?
  • 首字母是“Apple”吗?默认行为可能是该字段的可访问性标签是其内容,因此第二次尝试解析元素时查询失败。
  • 您应该在您的文本字段上设置一个可访问性标识符,并用它而不是“Apple”来查找它,以便它是一致的。每次您访问一个元素时,它都会尝试再次解析它。
  • 我明白你在说什么,我找到了 elementBoundByIndex() 的解决方法。谢谢帮助
【解决方案2】:

快 4.2。 您需要清除 textField 中的现有值并粘贴新值。

let app = XCUIApplication()
let textField = app.textFields["yourTextFieldValue"]
textField.tap()
textField.clearText(andReplaceWith: "VALUE")
XCTAssertEqual(textField.value as! String, "VALUE", "Text field value is not correct")

其中clearTextXCUIElement 扩展的方法:

extension XCUIElement {
    func clearText(andReplaceWith newText:String? = nil) {
        tap()
        press(forDuration: 1.0)
        var select = XCUIApplication().menuItems["Select All"]

        if !select.exists {
            select = XCUIApplication().menuItems["Select"]
        }
        //For empty fields there will be no "Select All", so we need to check
        if select.waitForExistence(timeout: 0.5), select.exists {
            select.tap()
            typeText(String(XCUIKeyboardKey.delete.rawValue))
        } else {
            tap()
        }
        if let newVal = newText {
            typeText(newVal)
        }
    }
}

【讨论】:

    【解决方案3】:

    以下内容适用于在 macOS 10.14.3 上运行的 Xcode 10.3,适用于运行 iOS 12.4 的 iOS 应用:

    XCTAssert( app.textFields["testTextField"].exists, "test text field doesn't exist" )
    let tf = app.textFields["testTextField"]
    tf.tap()    // must give text field keyboard focus!
    tf.typeText("Hello!")
    XCTAssert( tf.exists, "tf exists" )   // text field still exists
    XCTAssertEqual( tf.value as! String, "Hello!", "text field has proper value" )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-19
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多