Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UI Test: how to get message of UIAlertController

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?

like image 976
Luis Delgado Avatar asked Nov 12 '15 09:11

Luis Delgado


1 Answers

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:

Alert titled "You won!" with a message "Final Score: 27-25".

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.

like image 84
Joe Masilotti Avatar answered Nov 20 '22 15:11

Joe Masilotti