iosswiftui-automationxctestxctestcase

Sending app to background and re-launching it from recents in XCTest


I was looking for a solution to my problem where in I need to send my app to background and re-launch it from the recents after a particular time interval. deactivateAppForDuration() was used to achieve this in Instruments UIAutomation. Does anybody know how to achieve that in XCTest?


Solution

  • Not positive if this will work, as I haven't tested it yet, but it's worth a shot. If nothing else it should give you a good idea on where to look.

    XCUIApplication class provides methods to both terminate and launch your app programmatically: https://developer.apple.com/reference/xctest/xcuiapplication

    XCUIDevice class allows you to simulate a button press on the device: https://developer.apple.com/reference/xctest/xcuidevicebutton

    You can use these along with UIControl and NSURLSessionTask to suspend your application.

    An example of this process using Swift 3 might look something like this (syntax may be slightly different for Swift 2 and below):

    func myXCTest() {
    
        UIControl().sendAction(#selector(NSURLSessionTask.suspend), to: UIApplication.shared(), for: nil)
    
        Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(launchApp), userInfo: nil, repeats: false)   
    }
    
    func launchApp() {
        XCUIApplication().launch()
    }
    

    Another way may be simply executing a home button press, and then relaunching the app after a timer passes:

    func myXCTest {
    
        XCUIDevice().press(XCUIDeviceButton.Home)
    
        Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(launchApp), userInfo: nil, repeats: false)     
    }
    

    Neither of these ways may do what you're asking, or work perfectly, but hopefully, it will give you a starting point. You can play with it and find a solution that works for you. Good luck!