You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XCUITests中关闭/隐藏MacOS系统通知?

Mac端XCUITest运行时屏蔽系统通知污染截图的解决方案

针对Mac环境下无法使用iOS端springboard操作逻辑的问题,可通过以下三种方案解决:

方案1:测试前置全局禁用通知弹出(CI环境优先推荐)

该方案无需操作UI,稳定性最高,直接通过系统命令修改通知配置,从根源避免通知弹出:

  • 执行命令关闭通知横幅显示,执行后立即生效:
    defaults write com.apple.ncprefs.plist alertsEnabled -bool false && killall NotificationCenter
  • 测试执行完成后可执行以下命令恢复配置:
    defaults write com.apple.ncprefs.plist alertsEnabled -bool true && killall NotificationCenter

方案2:测试运行时动态清理已弹出通知

如果不希望修改全局系统配置,可通过操作Mac端负责通知展示的系统应用实现动态清理,对应bundle identifier为com.apple.notificationcenterui,适配代码示例如下:

// 每次截图前执行该清理逻辑
let notificationCenterApp = XCUIApplication(bundleIdentifier: "com.apple.notificationcenterui")
if notificationCenterApp.windows.firstMatch.exists {
    // 优先点击关闭按钮
    if notificationCenterApp.buttons["Close"].firstMatch.exists {
        notificationCenterApp.buttons["Close"].firstMatch.click()
    } else {
        // 无关闭按钮时触发ESC键关闭横幅
        notificationCenterApp.typeKey(.escape, modifierFlags: [])
    }
}

方案3:CI环境预开启勿扰模式

也可在测试任务启动前开启系统勿扰模式,实现通知屏蔽:

  • 开启勿扰模式命令:
    defaults -currentHost write com.apple.notificationcenterui doNotDisturb -bool true && killall NotificationCenter
  • 测试结束后恢复命令:
    defaults -currentHost write com.apple.notificationcenterui doNotDisturb -bool false && killall NotificationCenter

内容的提问来源于stack exchange,提问作者Paulius Liekis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:27:03