Neil Macy

Checking If A UI Test Is Running

When you write a UI test, you will often find you need to get the app into the right state to perform the test.

For example, you may have an onboarding flow that always runs on the first use after installing, but you want to test a different part of the app. You don't want to have to go through the onboarding flow every time you run an unrelated UI test flow. So you would want to skip this onboarding flow in your UI test, and focus on the specific flow that you're testing.

Your app probably has some logic like this already, to handle when this optional flow is shown:

if firstRun {

Are You Running Under UI Test Conditions?

When you start running your UI tests, you'll use UIApplication to launch the app. You can set its launchEnvironment to indicate UI tests:

let application = XCUIApplication()
application.launchEnvironment = ["UITests": "true"]

Then you can check the value:

let isUITesting = ProcessInfo.processInfo.environment["UITests"] == "true"

launchEnvironment is a dictionary of type [String: String], so the value doesn't have to be "true", it could be anything. So you can just check that some value is present for that key:

let isUITesting = ProcessInfo.processInfo.environment["UITests"] != nil

The key thing is not to set anything for "UITests" in this case when running normally!

Using This In Your App

To make sure you don't show your onboarding flow in UI tests, you can now add this value to your condition:

if firstRun && !isUITesting {

Published on 6 January 2022