XCUITest on macOS: side effects nobody warns you about
On iOS, UI tests run in a simulator you can throw away. On macOS they run on the Mac you’re using. Over a month of building out Purrchiver’s XCUITest suite, a lot of the failures I chased weren’t bugs in the app. Some were the tests changing the machine, some were the tests sharing state they shouldn’t, and a couple were the app being right and the test being wrong.
Here’s the list, with what fixed each one.
The app launched with zero windows
The first UI tests couldn’t find anything to click. Dumping the accessibility
tree at launch showed app.windows.count: 0, with only the menu bar
populated. Launching the app normally always opened a window.
The app delegate didn’t implement applicationShouldOpenUntitledFile(_:) or
applicationShouldHandleReopen(_:hasVisibleWindows:). In a normal launch,
AppKit’s default behavior opened the welcome window anyway. Under XCUITest it
apparently didn’t. Implementing both and returning true fixed it:
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool { true }
func applicationShouldHandleReopen(_ sender: NSApplication,
hasVisibleWindows flag: Bool) -> Bool { true }It also fixed a real bug: clicking the Dock icon with every window closed had done nothing. Now it opens a welcome window, like other Mac apps.
My Mac got stuck in Dark Mode
Xcode’s launch-test template sets
runsForEachTargetApplicationUIConfiguration = true, which runs the test once
per system appearance by writing the global AppleInterfaceStyle preference
between runs. When a run failed partway, nothing flipped it back, and my Mac
stayed in whichever appearance the last sub-run had set.
Two fixes. The flag is now false; light and dark coverage comes from snapshot
tests that render both color schemes without touching the system setting. And
the UI test bundle has an XCTestObservation that saves the appearance when
the bundle starts and restores it when the bundle finishes, as a safety net:
func testBundleWillStart(_ bundle: Bundle) {
saved = CFPreferencesCopyAppValue("AppleInterfaceStyle" as CFString,
kCFPreferencesAnyApplication) as? String
}
func testBundleDidFinish(_ bundle: Bundle) {
// Light mode is the key being absent, not a value.
run("/usr/bin/defaults",
saved.map { ["write", "-g", "AppleInterfaceStyle", $0] }
?? ["delete", "-g", "AppleInterfaceStyle"])
}The restore goes through /usr/bin/defaults because the test bundle couldn’t
write the global domain directly. The observer is registered by setting the
bundle’s NSPrincipalClass to the observer class.
Tests changed the Mac’s default archive app
Purrchiver’s onboarding and File Types settings can make it the default app for
archive types, through NSWorkspace.setDefaultApplication(at:toOpen:). UI
tests that walked through those screens did it for real: they reassigned the
test machine’s default handler for those types.
Each call also put up the system’s “open all files of this type with…” confirmation. Those dialogs belong to a system process, not the app, so they stacked up on screen and took focus. Later tests then clicked Settings tabs and hit nothing. That looked like a flaky Settings test for a while.
Both calls now return early when the app was launched by a UI test. The flows still run; the system side effect doesn’t happen.
Unit tests and UI tests shared one sandbox container
Hosted unit tests run inside the app. UI tests launch the app. For a sandboxed app, both use the same container: the same preferences, saved window state, and on-disk scratch space. Running the two suites at the same time gave two app instances racing on that state, and the failures were false, because a real user never runs two instances against one container.
The fix was ordering: UI tests now start only after the unit tests finish. Other projects run UI tests on the same test Mac too, so the runs also take a machine-wide lock first, and two projects’ UI suites never overlap.
A busy main thread became “Failed to terminate”
One end-to-end test extracts a RAR5 archive. While it runs, the main thread is busy enough that XCUITest’s accessibility snapshot sometimes times out. The timeout cancels the run, and the tests after it fail with “Failed to terminate”. One slow moment turned into a page of red.
Two changes. Each of those tests now terminates the app in tearDown, so every
test starts from a fresh launch and a failure doesn’t spread. And the UI test
plan retries a failed test up to three times. The plan that runs the unit tests
has no retries, so a real unit test failure still fails loudly.
A debug-only fatalError crashed half the suite
I’d added a #if DEBUG fatalError to the defaultValue of three
EnvironmentKeys. The idea: every window injects these values, so if
SwiftUI ever reads a default, some new window forgot to, and I want to know at
once.
SwiftUI reads EnvironmentKey.defaultValue while building the environment
even when the value has been injected with .environment(\.key, value). So
every UI test that opened a session window crashed in debug builds, about half
the suite. The stack ran through ChildEnvironment.updateValue, straight into
the default’s getter.
The defaults went back to returning the real shared instance. If I want that check back, it has to be something that doesn’t run inside SwiftUI’s own evaluation, such as a test that asserts the injection is in place.
A test that failed 14% of the time
This one wasn’t XCUITest, but it showed up on the same test machine. A test checked that two concurrent compress calls into an actor completed in the order they were submitted. On the CI runner it failed 3 times in 21 runs.
Swift actors guarantee that only one call runs at a time. They don’t guarantee that callers are served in the order they called. The test recorded which call “started first” by having each one check in with a second actor, and that’s a separate race: call A could check in first and still reach the compressor second. Nothing in the language promised otherwise.
The test now asserts what actors do promise: the two calls don’t interleave, both succeed, and both archives exist.
Running UI tests unattended
Running XCUITest needs macOS’s automation permission, and the first run on a machine asks someone to click Allow. On a dedicated test Mac nobody is there to click it, so runs sat waiting until they timed out. A configuration profile that grants the permission ahead of time fixed that, and the suite now runs without anyone at the keyboard.
What to take away
- Treat the test Mac as state the tests can change, and put back what they change: appearance, default apps, anything system-wide.
- Gate real system side effects behind “launched by a UI test”, not behind
#if DEBUG, so normal debug runs still do the real thing. - Don’t run two things that drive the same sandbox container at once.
- When a test fails a fixed percentage of the time, check what it assumes about ordering before you blame the runner.