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

Viewed 470

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?

2 Answers

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.

Related