可以将应用程序从后台带到前台吗?

时间:2016-02-09 14:53:04

标签: ios swift xcode7 xcode-ui-testing

运行XCT UI测试时,可以在后台运行测试应用程序:

XCUIDevice().pressButton(XCUIDeviceButton.Home)

可以通过某种方式将应用程序恢复到前台(活动状态)而无需重新启动应用程序吗?

5 个答案:

答案 0 :(得分:7)

Xcode 9的更新:从Xcode 9开始,您现在只需在任何XCUIApplication上调用activate()

let myApp = XCUIApplication()
myApp.activate() // bring to foreground

https://developer.apple.com/documentation/xctest/xcuiapplication/2873317-activate

是的,确实如此。但是,您需要XCUIElement的私有标头(可通过Facebook here的标头转储获得)。为了使应用程序前景化,您需要调用 resolve ,我相信它会解析元素的查询(对于应用程序来说,这意味着应用程序的前景)。

对于Swift,您必须将XCUIElement.h导入到桥接头中。对于Objective-C,您只需要导入XCUIElement.h。

应用程序背景:

夫特:

XCUIApplication().resolve()

目标-C

[[XCUIApplication new] resolve];

如果这是您需要的唯一功能,您可以编写一个快速的ObjC类别。

@interface XCUIElement (Tests)
- (void) resolve;
@end

如果您需要启动/解决其他应用。 Facebook has an example of that here by going through the Springboard.

答案 1 :(得分:4)

从Xcode 8.3和iOS 10.3开始,您可以使用Siri完成此任务:

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

在测试套件文件的顶部包含@available(iOS 10.3, *),您应该好好去!

答案 2 :(得分:1)

如果有人需要从背景中移回应用程序我已经写过(基于上面的答案)类别真的有效(非常感谢指向FB git)

@implementation XCUIApplication(SpringBoard)

+ (instancetype)springBoard
{
    XCUIApplication * springboard  = [[XCUIApplication alloc] performSelector:@selector(initPrivateWithPath:bundleID:)
                                                                   withObject:nil
                                                                   withObject:@"com.apple.springboard"];




    [springboard performSelector:@selector(resolve) ];
    return springboard;
}

- (void)tapApplicationWithIdentifier:(NSString *)identifier
{
    XCUIElement *appElement = [[self descendantsMatchingType:XCUIElementTypeAny]
                           elementMatchingPredicate:[NSPredicate predicateWithFormat:@"identifier = %@", identifier]
                           ];
    [appElement tap];
}
@end

答案 3 :(得分:0)

对于Swift,你需要在Brigding-Header.h中声明XCUIApplication私有方法接口,如下所示:

@interface XCUIApplication (Private)
- (id)initPrivateWithPath:(NSString *)path bundleID:(NSString *)bundleID;
- (void)resolve;
@end

然后在测试用例中调用resolve()以恢复应用程序:

XCUIApplication().resolve()

答案 4 :(得分:0)

这是我在XCUITest中拥有的功能,它就像一个魅力(xcode 10.1,测试设备是iPhone X 11.0)

func testWhatever(){

//您将测试步骤移至此处,直到需要后台运行为止

XCUIDevice.shared.press(XCUIDevice.Button.home)//后台应用程序 XCUIApplication()。activate()//将应用带回来

///在完成了背景前景后,您的测试将继续。 }

相关问题