簡體   English   中英

TextField 中的 Swift UI 測試訪問字符串

[英]Swift UI Testing Access string in the TextField

我正在使用集成在 Xcode 和XCTestUI Test Case類來測試應用程序 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 textField.value as! String方法; 這是行不通的。 我還嘗試將新的異步方法與expectationForPredicate() ,它會導致超時。

任何想法如何做到這一點或這種驗證是不可能的 UI 測試,我只能編寫黑盒測試?

我使用此代碼,它工作正常:

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

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

以下適用於運行在 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" )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM