如何解决单元测试UNUserNotificationCenterDelegate方法
我想对某些UNUserNotificationCenterDelegate
方法进行单元测试,尤其是userNotificationCenter(_,willPresent:,withCompletionHandler:)
为此,我必须创建一个UNNotification
的实例,但这实际上是不可能的,因为它只有一个initWithCoder
初始化程序。该怎么办?
这是我要测试的示例:
func userNotificationCenter(
_ center: UNUserNotificationCenter,willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler(.sound)
}
解决方法
由于this README和private 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)
}
享受!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。