9

我尝试测试一个简单的方法,该方法应该为 iOS 10 创建和传递通知。

func displayPlaceNotificationContent() {
    let unMutableNotificationContent = generateNotification()
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
    let request = UNNotificationRequest(identifier: getNotificationIdentifier(), content: unMutableNotificationContent, trigger: trigger)
    let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.add(request, withCompletionHandler: nil)
}  

这是此方法的单元测试:

func testDisplayNotification() {
    notificationManager?.displayPlaceNotificationContent())
    XCTAssertTrue((notificationManager.isNotificationDisplayed())
}

当我尝试执行单元测试时出现异常,堆栈跟踪:

2017-09-12 13:52:25.931564+0200 xctest[17170:1252988] *** Assertion failure in -[UNUserNotificationCenter initWithBundleProxy:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UserNotifications_Sim/UserNotifications-156/UNUserNotificationCenter.m:50
2017-09-12 13:52:25.933629+0200 xctest[17170:1252988] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: bundleProxy != nil'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010b0a9aeb __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010aa0cf41 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010b0aebb2 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x000000010a381d06 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
    4   UserNotifications                   0x000000010bff8c99 -[UNUserNotificationCenter initWithBundleProxy:] + 297
    5   UserNotifications                   0x000000010bff8a6f __53+[UNUserNotificationCenter currentNotificationCenter]_block_invoke + 81
    6   libdispatch.dylib                   0x0000000111a39475 _dispatch_client_callout + 8
    7   libdispatch.dylib                   0x0000000111a3a909 dispatch_once_f + 55
    8   UserNotifications                   0x000000010bff8a1b +[UNUserNotificationCenter currentNotificationCenter] + 45
...

由于 current() 方法,此失败的责任线应该是 UNUserNotificationCenter 的访问。我不明白为什么?UNUserNotificationCenter 应该是一个单例,我不能在单元测试上下文中使用它吗?我应该嘲笑它吗?

4

0 回答 0