问题描述
我想对某些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)
}
享受!