Swift: Timeout when unit testing orientation changes after upgrading to Xcode 10

Viewed 647

We recently upgraded from Xcode 8 to 10. After -finally- getting everything to compile again, I'm having an issue in our unit tests that involve orientation changes. What I had been doing to simulate device orientation changes was

    XCUIDevice.shared().orientation = .landscapeLeft
    ...
    XCUIDevice.shared().orientation = .faceUp
    ...
    etc.

Now when this line is executed, the "device" (simulator of iPhone 8+) is making the appropriate orientation change, but the call ultimately fails due to a timeout on the confirmation:

    [iMomTests.DataScreenTests testLandscape] : Failed to set orientation: Error Domain=XCTDaemonErrorDomain Code=15 "Timed out waiting for confirmation of orientation change." UserInfo={NSLocalizedDescription=Timed out waiting for confirmation of orientation change.}
2 Answers

This is an extension I came up with based on KIF's rotation method mentioned above.

public extension XCTestCase {
    public func waitUntilRotation(to orientation: UIInterfaceOrientation) {
        guard UIApplication.shared.statusBarOrientation != orientation else {
            return
        }
        UIDevice.current.setValue(orientation.deviceOrientation.rawValue, forKey:"orientation")
    }
}

Then, in the test case you call this method at the start to make sure the orientation is what you are expecting.

public func testSomethingInPortrait() {
    waitUntilRotation(.portrait)
    ...
}

We ended up extending KIFSystemTestActor and defining a rotate function:

func rotate(to orientation: UIDeviceOrientation) {
    self.simulateDeviceRotation(to: orientation)
}
Related