以编程方式将应用程序发送到后台

有没有办法将应用程序发送到后台? 与您如何调用XCUIApplication.terminate()类似,我有一些UI元素可以在applicationDidBecomeActive(_:)上进行testing。 有谁知道这是否可能?

我会build议检查XCUIDevice 。 这里是你如何可以按主页button,然后重新启动应用程序

 func testExample() { // Has a nav bar. XCTAssert(XCUIApplication().navigationBars.element.exists) XCUIDevice().press(XCUIDeviceButton.home) // Before Swift 3: XCUIDevice().pressButton(XCUIDeviceButton.Home) XCUIApplication().launch() // Navigationbar still there on second launch. XCTAssert(XCUIApplication().navigationBars.element.exists) } 

我刚试过UIApplication.sharedApplication().performSelector("suspend")成功。

 dispatch_after(2, dispatch_get_main_queue(), { // suspend the app after two seconds UIApplication.sharedApplication().performSelector("suspend") }) 

在Xcode 9.0中,Apple引入了XCUIApplication.activate()activate()将在必要时启动应用程序,但如果它已经在运行,则不会终止它。 从而:

 func testExample() { // Background the app XCUIDevice().press(.home) // Reactivate the app XCUIApplication().launch() }