XCUITest - 与锁屏通知交互

问题描述

我正在尝试编写一个 UI 测试,该测试在设备锁定后点击已发送的本地通知。到目前为止,我已经成功地点击了在跳板上传递的通知(当设备已经解锁时),但不是来自锁定屏幕。有谁知道这是否可能?

请注意,这与 from questions such as this one 不同,它只是点击主页按钮让应用程序处于测试状态并等待通知

这是我的测试代码的相关部分:

// ...already did stuff to schedule a local notification...
// Now lock screen
XCUIDevice.shared.perform(NSSelectorFromString("pressLockButton"))
// set up query for notification then wait
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
let notificationQuery : XCUIElementQuery = springboard
                    .otherElements["Notification"]
                    .descendants(matching: .any)
let notification = notificationQuery["MYAPP,Now,My Notification Header,Notification message body."]
// fails
XCTAssertTrue(notification.waitForExistence(timeout: 60))

如果我将调用替换为

XCUIDevice.shared.perform(NSSelectorFromString("pressLockButton"))

XCUIDevice.shared.press(.home)

然后测试通过。

感谢所有建议!

解决方法

我有类似的问题,我能够通过再次添加按下锁定来解决这些问题。这是工作代码。我使用 https://github.com/pterodactyl 作为通知。几年前我写了这段代码,现在仍然通过。

我做了两次同样的事情并且能够验证通知。一旦设备被锁定。你会看到一个黑屏,就像它被关闭了一样,当你第二次发送相同的代码时,它会打开设备,你可以得到通知元素进行测试

// 锁屏
XCUIDevice.shared.perform(NSSelectorFromString("pressLockButton"))
睡眠(1)

//第二次同样的命令,它会唤醒屏幕
XCUIDevice.shared.perform(NSSelectorFromString("pressLockButton"))

import PterodactylLib
import XCTest

func testRemotePush() {
    let app = XCUIApplication()
    app.launch()
    let pterodactyl = Pterodactyl(targetAppBundleId: "MOBILE APP BUNDLE ID")
    
    // did not find XCUI Protected Resources for Notifications
    // app.resetAuthorizationStatus(for: XCUIProtectedResource)
    
    XCTAssertTrue(
        app.buttons["loginButton"].waitForExistence(timeout: .superMaxTimeout),"Not able to launch App"
    )
    
    // Tap the home button
    XCUIDevice.shared.press(XCUIDevice.Button.home)
    sleep(1)
    
    // Trigger a push notification
    pterodactyl.triggerSimulatorNotification(withMessage: "Trust me ! I am notifications")
    sleep(1)
    
    // Lock the screen
    XCUIDevice.shared.perform(NSSelectorFromString("pressLockButton"))
    sleep(1)
    // same command second time,it will wake the screen
    
    XCUIDevice.shared.perform(NSSelectorFromString("pressLockButton"))
    
    // Tap the notification when it appears
    let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
    
    let notificationCell = springboard.buttons["NotificationCell"]
    XCTAssertTrue(notificationCell.waitForExistence(timeout: 150)) // implicity wait
    
    XCTAssertTrue(notificationCell.label.contains("Trust me ! I am notifications"))
}