Sebastian Hojas
Sebastian Hojas

Reputation: 4210

How to use a dynamic identifier to check for values of UI elements?

I am getting started with UI testing with Xcode and I am trying to check for the value of a UITextField. I can easily do this by

XCTAssertTrue(app.staticTexts[@"value of string"].exists);

I do, however, want to do the very same thing with dynamic content. Ideally, I would need something like

NSString* requiredValue = "computed string";
XCTAssertTrue(app.staticTexts[requiredValue].exists);

How can I implement this? I would greatly appreciated any hint or link to good resources that might answer this question.

Upvotes: 1

Views: 1874

Answers (1)

Joe Masilotti
Joe Masilotti

Reputation: 17008

You can reference the label via its accessibilityIdentifier instead of its content/value.

First set the identifier in your production code. This will also only show up during testing, not even for users with accessibility enabled.

UILabel *label = [[UILabel alloc] init];
label.accessibilityIdentifier = @"Username";
label.text = @"can be anything"; // just to prove the point

Then in your tests you can reference it.

XCTAssert(app.staticTexts[@"Username"].exists);

Here are a few references I've written for help with UI Testing:

Upvotes: 1

Related Questions