Get UILabel during UI testing


I'm trying to write a UI test which should assert if the text of a label is a specific string. I couldn't find any documentation and by diving into XCUIApplication code I was not able to find a specific query for a label.

Does anyone know how to get a label with a specific accessibility identifier and test its text value?

Thanks a lot.

Post not yet marked as solved Up vote post of Balestra Down vote post of Balestra


Found myself the answer by recording a tap on my label and see which code Xcode produces. It looks like this:

let app = XCUIApplication()
app.staticTexts.elementMatchingType(.Any, identifier: "Result").label

This does not work for me.

The text of my UILabel is from user input. When I use .staticTexts I only get the original label text (set in the storyboard), not the changed text.

Any ideas?

The only way I've found is to not set an Accessibility Label, but use identifier instead. Then XCUIElement.label will change to match the current text of the label.

However there is a gotcha: if you have previously set Accessibility Label in XC, and remove it, an entry setting the label to "" remains in the storyboard. In this case, not only will calling .label will return "", but you won't be able to query for the label by it's text!

The ony thing you can do is delete and re-add the label, or manually edit the xml.

Thank you so much for this tip! I've been struggling to figure out why I couldn't get my label's text during my XCTest run. Your solution worked great!

Just three letters: O M G

Thank you for this insight into the ridiculous behaviour of XCode!

according to me this is a bug. Bug added 23629078