Chrishan
Chrishan

Reputation: 4106

Access elements in a custom view component in Swift 3 UI testing

I'm a newbie to any type of iOS programming. I am trying to write UI test cases for one of my scenes.

Following is the code I'm getting when I use recode method and tap on the custom component.

let button = XCUIApplication().children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .button).element

In this custom component there are two buttons. I wanna know which button is selected. For that I need to identify the button. But i'm getting same code where ever I tap on the custom view.

How can I access each component inside custom view. Any help would be great.

Upvotes: 2

Views: 3906

Answers (2)

Oletha
Oletha

Reputation: 7639

Add an accessibility identifier to your custom view in the app's code.

let customView: UIView!
customView.accessibilityIdentifier = "myCustomView"

Then access the contents like this:

let app = XCUIApplication()
let customView = app.otherElements["myCustomView"]
let button1 = customView.buttons.element(boundBy: 0)
let button2 = customView.buttons.element(boundBy: 1)
XCTAssertTrue(button1.isSelected)
XCTAssertFalse(button2.isSelected)

Note that to make your test deterministic, you should already know which button(s) should be selected. This ensures that your test tests the same thing every time it is run.

Upvotes: 12

Titouan de Bailleul
Titouan de Bailleul

Reputation: 12949

You need to make you elements visible to Accessibility.

I would suggest you to watch the WWDC Session about UI Testing in Xcode especially this part

Upvotes: 0

Related Questions