Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UI Testing Access string in the TextField

Tags:

I am using the UI Test Case class integrated in Xcode and XCTest to test app UI. I want to test something like this:

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

I've tried the textField.value as! String method; it does not work. I've also tried using the new async method with expectationForPredicate(), and it will result in a timeout.

Any idea how to do this or validation of this kind is not possible with UI Test and I could only write black-box tests?

like image 390
leoluo Avatar asked Nov 18 '15 22:11

leoluo


2 Answers

I use this code and it works fine:

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

If you're doing something similar and it isn't functioning, I would check to make sure that your textField element actually exists:

XCTAssertTrue(textField.exists, "Text field doesn't exist") textField.typeText("value") XCTAssertEqual(textField.value as! String, "value", "Text field value is not correct") 
like image 134
Charles A. Avatar answered Sep 17 '22 01:09

Charles A.


Swhift 4.2. You need to clear an existing value in textField and paste 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 a method of XCUIElement extension:

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)         }     } } 
like image 30
Agisight Avatar answered Sep 17 '22 01:09

Agisight