问题描述
我对何时使用expectationForNotification as opposed to
expectationWithDescription`感到困惑.我一直无法迅速找到任何清晰的示例来说明此调用的时间和作用.
I'm a little confused as what/when to do with expectationForNotification as opposed to
expectationWithDescription`. I've been unable to find any clear examples in swift for when and what you do with this call.
我假设它也许可以测试通知,但是看起来它可能是通知中心整个addObserver()
调用的一个更方便的包装.
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?
推荐答案
正如您已经想到的, expectationForNotification 是检查通知是否已发出的一种方便期望.
As you have already imagined expectationForNotification is a convenience expectation for checking if a notification was raised.
该测试:
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)
}
可以用以下内容代替:
func testItShouldRaiseAPassNotificationV2() {
expectationForNotification("evPassed", object: nil, handler: nil)
NSNotificationCenter.defaultCenter().postNotificationName("evPassed", object: nil)
waitForExpectationsWithTimeout(0.1, handler: nil)
}
您可以在此 Objc.io号中找到很好的解释.
You can find a good explanation in this Objc.io number.
这篇关于在什么情况下会在快速测试中使用ExpectationForNotification的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!