Search code examples
swiftxcuitest

XCUITest to background the app is returning the wrong XCUIApplication.State


I have a XCUITest that requires the app to be put in the background. My understanding was that when pressing the home button the app would be put into the background, which I have coded as such:

XCUIDevice.shared.press(.home)
sleep(2)
XCTAssertEqual(app.state, .runningForeground)

However, as the assertion states, the app is seemingly running in the foreground. Is this an incorrect implementation on my part?


Solution

  • iOS Apps do not go to the background immediately – they have time to save data in case the app will be terminated in future. https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background

    Furthermore .state returns the results asynchronously. Read more in Discussion https://developer.apple.com/documentation/xctest/xcuiapplication/2877401-state

    That's the reason you should use wait function as you did in your own answer https://developer.apple.com/documentation/xctest/xcuiapplication https://developer.apple.com/documentation/xctest/xcuiapplication/2921487-wait