Swift UI测试:访问TextField中的字符串

22

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

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测试无法进行这种验证,只能编写黑盒测试?


感谢@Charles A.指出问题是textField不存在。我很困惑,因为我调用了typeText方法,我可以看到文本被输入到了textField中。 - leoluo
3个回答

43
我使用这段代码,它可以正常运行:

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不存在。但我不明白这一点:我在textField上调用typeText,我可以看到文本被输入到textField中。 - leoluo
我应该在这个方法上使用异步吗? - leoluo
最初的文本是“Apple”吗?默认行为可能是字段的可访问标签就是其内容,因此当您尝试解析元素第二次时,查询将失败。 - Charles A.
你应该在文本框上设置可访问标识符,并使用它来查找,而不是使用“Apple”进行查找,以保持一致性。每次访问元素时都会尝试重新解析它。 - Charles A.
1
我理解你的意思,并且通过elementBoundByIndex()找到了一个解决方法。感谢你的帮助。 - leoluo
显示剩余2条评论

3

Swift 4.2。 您需要清除文本框中的现有值并粘贴新值。

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)
        }
    }
}

2

以下内容适用于运行在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" )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接