【问题标题】:How write unit test for receiving nsnotification asynchronous?如何编写单元测试来异步接收nsnotification?
【发布时间】:2016-03-26 02:10:16
【问题描述】:

我用完成处理程序调用 rest web 服务,如果成功我发送 NSNotification。

问题是如何编写单元测试来断言在成功的情况下发送通知。

任何帮助将不胜感激。

【问题讨论】:

标签: ios swift nsnotificationcenter xctest nsnotification


【解决方案1】:

这是我测试通知的方式:

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)
}

【讨论】:

    【解决方案2】:

    您可以为通知添加期望:

    expectationForNotification("BlaBlaNotification", object: nil) { (notification) -> Bool in
    
    // call the method that fetches the data
    sut.fetchData()  
    
    waitForExpectationsWithTimeout(5, handler: nil)
    

    但我个人认为这是两个测试。一种用于获取数据(使用存根测试),另一种用于发送通知。

    【讨论】:

    • sutsystem under test 的缩写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多