How to write unit test for NSNotification

后端 未结 3 1321
野性不改
野性不改 2020-12-31 04:23

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 i

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 04:41

    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.

提交回复
热议问题