单元测试UNUserNotificationCenterDelegate方法

问题描述

我想对某些UNUserNotificationCenterDelegate方法进行单元测试,尤其是userNotificationCenter(_,willPresent:,withCompletionHandler:)

为此,我必须创建一个UNNotification的实例,但这实际上是不可能的,因为它只有一个initWithCoder初始化程序。该怎么办?

这是我要测试的示例:

func userNotificationCenter(
    _ center: UNUserNotificationCenter,willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
    completionHandler(.sound)
}

解决方法

由于this READMEprivate iOS headers here,我想出了以下解决方案:

func testUserNotificationCenterDelegate() throws {
    // Create the notification content
    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "Test"
    notificationContent.userInfo = ["someKey": "someValue"]
    
    // Create a notification request with the content
    let notificationRequest = UNNotificationRequest(identifier: "test",content: notificationContent,trigger: UNTimeIntervalNotificationTrigger(timeInterval: 0.1,repeats: false))
    
    // Use private method to create a UNNotification from the request
    let selector = NSSelectorFromString("notificationWithRequest:date:")
    let unmanaged = UNNotification.perform(selector,with: notificationRequest,with: Date())
    let notification = unmanaged?.takeUnretainedValue() as! UNNotification
    
    // Test the method
    let callbackExpectation = XCTestExpectation(description: "Callback")
    pushService.userNotificationCenter(UNUserNotificationCenter.current(),willPresent: notification) { (options) in
        XCTAssertEqual(options,.sound)
        callbackExpectation.fulfill()
    }
    wait(for: [callbackExpectation],timeout: 2.0)
}

享受!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...