Search code examples
xcodexctestxcode-ui-testing

avoiding app state restoration in XCTest UI Testing


I'm writing UI Tests for a document-based macOS app.

The test opens a template document by clicking a button in a splash-screen window (much like the "Welcome to Xcode" window). This works on the first test run. But subsequent launches are foiled by state restoration as the previously opened document is covering the splash-screen window.

How can I disable state restoration when running Xcode UI tests?

I've disabled state restoration in my app target ("Launch application without state restoration"), which works fine. But this doesn't carry over to the test target, even when "Use the Run Action's arguments and environment variables" is checked.

I've also tried to close the previously opened document at the end of the test, but "Record UI Test" doesn't record anything when I click on "Delete Copy" in the save dialog.


Solution

  • This did the trick in the test's setUp function:

    let app = XCUIApplication()
    app.launchArguments.append(contentsOf: ["-ApplePersistenceIgnoreState", "YES"])
    app.launch()
    

    You can also append the equivalent argument directly on the command line, e.g.:

    /Applications/Example.app/Contents/MacOS/example -ApplePersistenceIgnoreState YES