Aaron Vegh Aaron Vegh - 4 months ago 29
iOS Question

Xcode UI Testing: Executing a Test Conditionally

Using Xcode UI Testing, I want to implement code that runs if a particular UI element in present in the app. My app has a logged-in state and I want to log the user out if they are currently logged in. I've been unable to find documentation to suggest a way out of this paper bag.

Everything I've read shows two possible paths: using

XCTAssert
(which would cause my test to fail immediately if the element weren't present) and using
XCTExpectation
(which would cause my test to time out if the element weren't present). I need a more simple way to run different code if the app is in a given state.

To put it in code, I'm looking for something like this:

if let signOutElement = app.collectionViews.staticTexts["Sign Out"] {
signOutElement.tap()
}


Alas, this doesn't work.

Answer

There's nothing wrong with using a conditional during testing. The problem with your code is that it is nonsense from a Swift point of view; if let is meaningless here, as your expression does not return an Optional. You do still have to talk legal Swift, after all.

Why not try something like this?

if app.collectionViews.staticTexts["Sign Out"].exists