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

Possible to bring the app from background to foreground?

当 运行 XCT UI 测试时,可以将应用程序置于后台进行测试:

XCUIDevice().pressButton(XCUIDeviceButton.Home)

是否可以通过某种方式使应用程序回到前台(活动状态)而无需重新启动应用程序?

Xcode9 的更新:从Xcode9 开始,您现在可以在任何 XCUIApplication 上简单地调用 activate()

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

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


是的,是的。但是,您将需要 XCUIElement 的私有 headers(可通过 header 从 Facebook here 转储获得)。为了将应用程序置于前台,您需要调用 resolve ,我相信它可以解决元素的查询(对于应用程序而言意味着将应用程序置于前台)。

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

应用后台运行:

Swift:

XCUIApplication().resolve()

Objective-C

[[XCUIApplication new] resolve];

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

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

如果您需要启动/解析另一个应用程序。 Facebook has an example of that here by going through the Springboard.

如果有人需要将应用程序从后台移回,我已经写了(基于上面的回答)真正有效的类别(非常感谢指向 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

对于Swift,您需要像这样在Bridging-Header.h中声明XCUIApplication私有方法接口:

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

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

XCUIApplication().resolve()

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

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

在测试套件文件的顶部包含 @available(iOS 10.3, *),您应该可以开始了!

这就是我在 XCUITest 中拥有的东西,它非常有用(xcode 10.1,测试设备是 iPhone X 11.0)

func testWhatever() {

//你测试步骤到这里,直到你需要背景前景到运行

XCUIDevice.shared.press(XCUIDevice.Button.home) // 应用后台 XCUIApplication().activate() // 恢复应用

// 背景前景完成后继续测试。 }

从 Xcode 13 开始,我们遇到了几个错误,表明在返回应用程序后应用程序未处于前台状态。

将此代码应用于我们的“goToSpringboardAndBack()”作品

XCUIDevice.shared.press(XCUIDevice.Button.home)
if XCUIApplication().wait(for: .runningBackground, timeout: 5.0) {
   XCUIApplication().activate()
}

_ = XCUIApplication().wait(for: .runningForeground, timeout: 5.0)
´´´