How to retrieve variable data from a label in UI tests
Asked Answered
M

1

10

This is what I have so far and I am simply trying to get the result that is output in a label and test it against set results:

func testExample() {

    let app = XCUIApplication()
    let enterRomanNumeralsHereTextField = app.textFields["Enter roman numerals here"]
    enterRomanNumeralsHereTextField.tap()
    let convertButton = app.buttons["Convert"]

    //1
    enterRomanNumeralsHereTextField.typeText("LL")
    convertButton.tap()
    XCTAssertTrue(app.staticTexts.element(matching:.any, identifier: "Roman Numerals").label == "NotValidRomanNumber")


    //2
    enterRomanNumeralsHereTextField.typeText("LXXXIX")
    convertButton.tap()
    XCTAssertEqual(app.otherElements.containing(.staticText, identifier:"Roman Numerals").element.value as! String, "89")

    //3
    enterRomanNumeralsHereTextField.typeText("")
    enterRomanNumeralsHereTextField.typeText("LXXVIII")
    convertButton.tap()
    XCTAssertEqual(app.otherElements.containing(.staticText, identifier:"Roman Numerals").element.value as! String, "")



    // Use recording to get started writing UI tests.
    // Use XCTAssert and related functions to verify your tests produce the correct results.
}

The first attempt(labeled 1) gives me a build error saying "cannot call value of non function type XCUIElement. The second attempt builds but the test fails because even though the label does indeed produce the right value, the test is reading the label as blank which brings us to my third attempt which passes the test because I compared it to a blank label, which is what its showing.

So as I said above I'm just wondering how exactly to retrieve the label value that is a result of a "calculation" or button press.

Mottle answered 31/5, 2017 at 15:54 Comment(0)
B
21

Unfortunately when a UILabel is accessed in a UITest the XCUIElement's value property is not set with the text property of the UILabel. It is always empty.

XCUIElement also has a label property which you can use for your purpose. You only have to make sure that you are not setting the accessibilityLabel on your UILabel. Use accessibilityIdentifier instead:

In your app:

label.accessibilityIdentifier = "Roman Numerals"

In your UITest:

XCTAssertEqual(app.staticTexts.element(matching:.any, identifier: "Roman Numerals").label, "89")
Baldwin answered 10/6, 2017 at 15:36 Comment(4)
I really had a lot of trouble with it. Thanks.Buckie
@joem How did you find out about which property to use ??Menace
@Menace I had a look at ˋXCUIElementAttributesˋ which ˋXCUIElementˋ conforms to. That protocol defines the exposed attributes for all UI elements. Then I just had a look at those attributes‘ values in case you query a ˋUILabelˋ.Baldwin
@joem Thanks a lot. I will look there when I am stuck tooMenace

© 2022 - 2024 — McMap. All rights reserved.