Swift UI Testing Access String in TextField

I use the UI test case class integrated in Xcode and XCTest to test the user interface of the application. I want to check something like this:

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

I tried textField.value like! String this does not work. I also tried using the new async method with expectationForPredicate () , and this will result in a timeout.

Any ideas how to do this? Or is verification of this type impossible when testing the user interface, and I can only write tests with a "black box"?

+11
ios swift xcode-ui-testing
source share
3 answers

I use this code and it works great:

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

If you do something like this and it doesn't work, I would check to make sure your textField element really exists:

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

Swhift 4.2. You need to clear the existing value in textField and insert a new value.

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

where clearText is the XCUIElement extension XCUIElement :

 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) } } } 
+1
source share

the following works on Xcode 10.3 running on macOS 10.14.3 for an iOS application running on iOS 12.4:

 XCTAssert( app.textFields["testTextField"].exists, "test text field does not 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" ) 
0
source share

All Articles