rachit
rachit

Reputation: 1996

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?

Upvotes: 9

Views: 4170

Answers (3)

Bill Chan
Bill Chan

Reputation: 3455

Update for Xcode 14:

        XCUIDevice.shared.press(XCUIDevice.Button.home)
        sleep(30)
        XCUIApplication().launch()

Upvotes: 0

brandenbyers
brandenbyers

Reputation: 496

If you can use Xcode 8.3 and iOS 10.3 with your current tests, then you might want to try this:

XCUIDevice.shared().press(XCUIDeviceButton.home)
sleep(60)
XCUIDevice.shared().siriService.activate(voiceRecognitionText: "Open {appName}")

Be sure to include @available(iOS 10.3, *) at the top of your test suite file.

This will be relatively equivalent to deactivateAppForDuration(). Just change the sleep() to your desired duration.

Upvotes: 4

user3353890
user3353890

Reputation: 1891

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!

Upvotes: 7

Related Questions