swiftmockingtdd

Mock UNNotificationResponse & UNNotification (and other iOS platform classes with init() marked as unavailable)


I need to mock UNNotificationResponse and UNNotification so that I can test my implementation of:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void)

However I can't usefully subclass these classes because init() is specifically marked as unavailable, resulting in compilation errors like this if I try:

/Path/to/PushClientTests.swift:38:5: Cannot override 'init' which has been marked unavailable

What alternate approaches can be taken here? I look into going down the Protocol Oriented Programming route, however since I do not control the API being called, I can't modify it to take the protocols I'd write.


Solution

  • Short answer: You can't!

    Instead, decompose your implementation of

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void)
    

    and test the methods you call from there, instead.

    Happy testing :)