How write unit test for receiving nsnotification asynchronous?
Asked Answered
J

2

8

I call rest web servic with completion handler and if succeed I send NSNotification.

The problem is how to write unit test to assert that the notification is sent in case of success.

Any help will be appreciated.

Jasonjasper answered 19/12, 2015 at 13:31 Comment(1)
xctestexpectation, for example, could solve your problem as async invocationsPhraseogram
C
10

You can add an expectation for the notification:

expectationForNotification("BlaBlaNotification", object: nil) { (notification) -> Bool in

// call the method that fetches the data
sut.fetchData()  

waitForExpectationsWithTimeout(5, handler: nil)

But personally I would split this is two tests. One for the fetching of the data (tested using a stub) and one for the sending of the notification.

Chauvin answered 19/12, 2015 at 15:4 Comment(1)
sut is short for system under test.Chauvin
B
1

This is how I test notifications:

func testDataFetched() {

    weak var expectation = self.expectation(description: "testDataFetched")

    //set the notification name to whatever you called it
    NotificationCenter.default.addObserver(forName: NSNotification.Name("dataWasFetched"), object: nil, queue: nil) { notification in

        //if we got here, it means we got our notification within the timeout limit

        //optional: verify userInfo in the notification if it has any

        //call fulfill and your test will succeed; otherwise it will fail
        expectation?.fulfill()
    }

    //call your data fetch here
    sut.fetchData()

    //you must call waitForExpectations or your test will 'succeed'
    // before the notification can be received!
    // also, set the timeout long enough for your data fetch to complete
    waitForExpectations(timeout: 1.0, handler: nil)
}
Bowsprit answered 16/4, 2020 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.