A simple scenario: You are writing a UITest that should check if a UISwitch is switched on.
In a UnitTest you would simply do this:
When you are running a UITest you cannot do that, because during a running UITest you cannot access the UISwitch directly. Xcode only gives you access to your app’s UI elements via the XCUIElement class. That class is used for all accessible UI elements so it does not have a isOn property like UISwitch has.
So how do you test that the UISwitch is on?
It’s actually pretty easy, but not really obvious. XCUIElement conforms to XCUIElementAttributes which gives you access to a value property of type Any?
So, as value can literally be Any(thing) I tried to cast it to a Bool, because isOn also is a Bool, right?
Not working! Turns out that when you access a UISwitch in your UITest its value property is of type NSTaggedPointerString. Which is a subclass of NSString and can be cast to String (when you are using Swift). So the Bool isOn value has been mapped to a “0” or “1” String.
To test if the first UISwitch in your current view has been switched on, you can do this in a UITest:
let firstSwitch = app.switches.element(boundBy: 0)
XCTAssertEqual(firstSwitch.value as! String, "1")
If you want to access your UISwitch via the accessibility identifier you can do it like this:
let mySwitch = app.switches["MySwitchIdentifier"]