Skip to content

Instantly share code, notes, and snippets.

@mdb1
Created August 12, 2023 23:20

Revisions

  1. Manu Herrera created this gist Aug 12, 2023.
    42 changes: 42 additions & 0 deletions NotificationCenterMock.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    /// Mock instance of NotificationCenter, to be used in tests' targets
    public final class NotificationCenterMock: NotificationCenter {
    public var postCalls = 0
    public var postedNotifications: [NSNotification.Name] = []
    public var postReceivedObject: Any?
    public var postReceivedUserInfos: [[AnyHashable: Any]] = []

    public var addObserverCalls = 0
    public var addObserverReceivedSelector: Selector?
    public var addObserverReceivedName: NSNotification.Name?
    public var addObserverReceivedObject: Any?

    /// Initializer
    override public init() {}
    }

    public extension NotificationCenterMock {
    override func post(name aName: NSNotification.Name, object anObject: Any?, userInfo: [AnyHashable: Any]?) {
    postCalls += 1
    postedNotifications.append(aName)
    postReceivedObject = anObject
    if let userInfo {
    postReceivedUserInfos.append(userInfo)
    }
    super.post(name: aName, object: anObject, userInfo: userInfo)
    }
    }

    public extension NotificationCenterMock {
    override func addObserver(
    _ observer: Any,
    selector aSelector: Selector,
    name aName: NSNotification.Name?,
    object anObject: Any?
    ) {
    addObserverCalls += 1
    addObserverReceivedSelector = aSelector
    addObserverReceivedName = aName
    addObserverReceivedObject = anObject
    super.addObserver(observer, selector: aSelector, name: aName, object: anObject)
    }
    }