Topics

#129: More UI Testing Tips 🚸

Topics

Today we'll look at a couple more tips to get the most out of UI Testing in Xcode. (Covered previously in Bites #30, and #124).

Are We in a Test?

It'd be great if our app could know when it's running inside of a UI Test, then behave differently. We'll start by setting a flag that we can check for later. We'll add a launchArgument before we launch our app in our tests' setUp functions.

let app = XCUIApplication()
app.launchArguments = [ "IS_UI_TESTING" ]
app.launch()

Then, we'll add a new helper function to our app's code. We could add this to a helper class, or just make it a global function:

func isUITesting() -> Bool {
  return Process.arguments.contains("IS_UI_TESTING")
}

We can use this function throughout our code to do things like hit mock servers during testing, or simulate a camera preview when capturing screenshots with snapshot. (Bite #110).

Dismissing System Alerts

We have to jump through a couple of hoops here. First we'll need to set up what's called a "UI Interruption handler", which will execute a closure when the UI is interrupted by, for example, an alert being shown:

addUIInterruptionMonitorWithDescription("Authorization Prompt") {
  $0.buttons["Allow"].tap()
  return true
}

app.tap()

Then, after our app presents the authorization prompt, we'll need to .tap() on it once before the UI Interruption handler will fire. Inside our handler, we'll accept the prompt then return true to tell Xcode we've handled the UI interruption.

Have a UI Testing tip or trick of your own you'd like share? Send it along to hello@littlebitesofcocoa.com!