user1162328
user1162328

Reputation:

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?

Upvotes: 2

Views: 931

Answers (2)

Roman Zakharov
Roman Zakharov

Reputation: 2273

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

Upvotes: 2

user1162328
user1162328

Reputation:

Replacing...

sleep(5)
XCTAssertEqual(app.state, .runningForeground)

with...

let background = app.wait(for: .runningBackground, timeout: 5)
XCTAssertTrue(background)

has resolved the issue.

I guess I had to explicitly wait for the expected state to happen.

Upvotes: 3

Related Questions