Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 814
rachit Avatar asked Nov 17 '16 11:11

rachit


2 Answers

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!

like image 126
user3353890 Avatar answered Nov 07 '22 09:11

user3353890


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.

like image 41
brandenbyers Avatar answered Nov 07 '22 08:11

brandenbyers