How to write unit test for NSNotification

user2413621 picture user2413621 · Feb 3, 2015 · Viewed 11.2k times · Source

I am working in swift, I want to refresh a page so I am sending it using notification, I am posting a notification in one ViewController and adding observer in another and it is working perfectly. What I want to do is add unit test to it in swift. I checked many sites but was not able to do it. I am new to swift and don't know where to start.

Basically the working is, when i click the button notification is posted and when the next view controller is loaded the notification observer is added.

How can I do the unit testing

Thanks in advance

Edit: Code

NSNotificationCenter.defaultCenter().postNotificationName("notificationName", object: nil)

and adding observer as

NSNotificationCenter.defaultCenter().addObserver(self, selector: "vvv:",name:"notificationName", object: nil)

Answer

zpasternack picture zpasternack · Aug 3, 2018

XCTest has a class specifically for testing Notifications: XCTNSNotificationExpectation. You create one of these expectations, and it's fulfilled when a notification is received. You'd use it like:

// MyClass.swift
extension Notification.Name {
    static var MyNotification = Notification.Name("com.MyCompany.MyApp.MyNotification")
}

class MyClass {
    func sendNotification() {
        NotificationCenter.default.post(name: .MyNotification,
                                      object: self,
                                    userInfo: nil)
    }
}


// MyClassTests.swift
class MyClassTests: XCTestCase {
    let classUnderTest = MyClass()

    func testNotification() {
        let notificationExpectation = expectation(forNotification: .MyNotification, 
                                                           object: classUnderTest, 
                                                          handler: nil)

        classUnderTest.sendNotification()

        waitForExpectations(timeout: 5, handler: nil)
    }
}

XCTestCase's expectation(forNotification:object:handler:) is a convenience method to create an instance of XCTNSNotificationExpectation, but for more control, you could instantiate one and configure it yourself. See the docs.