UI Testing: UILabel

I watched the WWDC talk on UITesting a couple of times. Used the accessibility fields in Interface Builder to give the buttons and labels names. Got recording working. I am writing a simple calculator app. It has buttons and a UILabel for its display. The problem is that I can't seem to find the property of the UILabel which contains its current text.

let app = XCUIApplication()
app.buttons["OneKey"].tap()
app.buttons["TwoKey"].tap()
app.buttons["ThreeKey"].tap()
XCTAssertEqual(app.otherElements["MainDisplay"].value as? String, "123", "Whole number Entry-Main Display")
Assertion Failure: XCTAssertEqual failed: ("Optional("")") is not equal to ("Optional("123")") - Whole number Entry-Main Display
Optional("Main Display")

The assertion fails and says that the MainDisplay text is "" blank. I used the debugger to dump the .debugDescription of the staticTexts and can find no useful properties. I tryed .value, .textFields, .description

(lldb) p print(app.otherElements["MainDisplay"].staticTexts as? String)
nil
(lldb) p print(app.otherElements["MainDisplay"].textFields as? String)
nil
(lldb) p print(app.otherElements["MainDisplay"].value as? String)
Optional("")

Anyone know what I am doing wrong?


By The Way, whats with the illegal characters error when it doesn't like your title?

Any updates on this??

Were you able to find out the right method to click on a label.

Hey,


By default, a UILabel propagates its text as its accessibilityLabel. This can be inspected in UI tests as element.label. For your use case, I imagine "Main Display" or "Result" is set as the accessibilityLabel of your label, as such element.label would return that instead of the text.


What you can do is manually update the `accessibilityValue`of your label whenever you update the result. You can streamline that by creating a small UILabel subclass that automatically updates its accessibility value based on its text so you don't have to.


class ResultLabel: UILabel {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        accessibilityValue = text
    }

    override var text: String? {
        didSet {
            accessibilityValue = text
        }
    }
}


This will then allow you to inspect the value in UI tests via element.value.


    func testResultLabel() {
        let app = XCUIApplication()
        let resultLabel = app.staticTexts["Result"]
        XCTAssertEqual(resultLabel.value as? String, "205") // Or whatever value you expect it to be
    }


In addition this would make your application more accessible! For example while using Voice Over, it would say "Result, 205"!


Hope this helps.

UI Testing: UILabel
 
 
Q