My app has a login screen. If the user presses the login button without entering any text in either the username or password fields, the app will display a UIAlertController
with an error message.
I am trying to model this logic in UI Tests, and want to assert that the UIAlertController
is displaying the correct message. However, I can't find a way for the UI Test to access the message property of the alert. Here is the code generated by the test recorder:
func testLoginWithoutPasswort() {
let app = XCUIApplication()
let emailTextField = app.textFields["email"]
emailTextField.tap()
emailTextField.typeText("[email protected]")
app.buttons["Login"].tap()
app.alerts["Error"].collectionViews.buttons["OK"].tap()
}
Is there any way I can extract the String
value of the alert's message, so I can put an assertion on it?
You can't directly test the alert's message. You can, however, test if the alert contains your error message's copy (at all).
For example, say your alert looks like this:
To assert that the alert contains the "Final Score" message, use:
XCTAssert(app.alerts.element.staticTexts["Final Score: 27 - 25"].exists)
You can also test the title of the alert directly:
XCTAssertEqual(app.alerts.element.label, "You won!")
More examples available in my UI Testing Cheat Sheet and Examples post and sample app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With