如何在 Xcode UITest 期间关闭系统对话框

How to dismiss a system dialog during a Xcode UITest

在我的单元测试中,有一个页面要求允许使用库。当我的单元测试 运行ning 时,此权限对话框出现在屏幕上,并且即使我的所有单元测试都完成也不会消失。当 UI 测试尝试 运行 时,它们不会导致此对话框。在单元测试之前有什么方法可以 运行 UI 测试吗?

所以你真正的问题是在 运行 UITests 时摆脱系统对话框。 运行 单元测试之前的 UITest 不会改变任何东西,因为系统对话框会在 UITest 期间弹出。

您可以像这样关闭对话框(在您的 UITest 中):

addUIInterruptionMonitor(withDescription: "“RemoteNotification” Would Like to Send You Notifications") { (alerts) -> Bool in
   if(alerts.buttons["Allow"].exists){
      alerts.buttons["Allow"].tap();
   }
   return true;
}
XCUIApplication().tap()

您必须更改描述,因为上面的代码消除了请求发送推送通知权限的系统警报。

请务必在您的测试触发系统对话框之前使用此代码。您可以在启动应用程序之后和测试执行任何其他操作之前立即将其放入测试函数中。

如果您使用的是 XCode9,您可以直接与对话框进行交互:

let systemAlerts = XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts
if systemAlerts.buttons["Allow"].exists {
    systemAlerts.buttons["Allow"].tap()
}

``

对我来说只有这个成功了:

 DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
    //replace this "OK" with your button title
    springboard.alerts.buttons["OK"].tap()
}

     tapButtonThatTriggersThePermissionsDialog()