In what situation would one use expectationForNotification in swift testing

Jeef picture Jeef · Apr 22, 2015 · Viewed 7k times · Source

I'm a little confused as what/when to do with expectationForNotification as opposed toexpectationWithDescription`. I've been unable to find any clear examples in swift for when and what you do with this call.

I'm assuming its perhaps to test notifications but it looks like it might just be a more convenient wrapper around the whole addObserver() call of notification center.

Could somebody give a brief explanation of what it does, when to use it, and perhaps a few lines of sample code?

Answer

Giordano Scalzo picture Giordano Scalzo · Apr 22, 2015

As you have already imagined expectationForNotification is a convenience expectation for checking if a notification was raised.

This test:

func testItShouldRaiseAPassNotificationV1() {
    let expectation = expectationWithDescription("Notification Raised")
    let sub = NSNotificationCenter.defaultCenter().addObserverForName("evPassed", object: nil, queue: nil) { (not) -> Void in
        expectation.fulfill()
    }
    NSNotificationCenter.defaultCenter().postNotificationName("evPassed", object: nil)
    waitForExpectationsWithTimeout(0.1, handler: nil)
    NSNotificationCenter.defaultCenter().removeObserver(sub)
}

can be replaced by this one:

func testItShouldRaiseAPassNotificationV2() {
    expectationForNotification("evPassed", object: nil, handler: nil)
    NSNotificationCenter.defaultCenter().postNotificationName("evPassed", object: nil)
    waitForExpectationsWithTimeout(0.1, handler: nil)
}

You can find a good explanation in this Objc.io number.