如何编写接收NSNotification异步的单元测试?

8

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

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

任何帮助将不胜感激。


1
例如,xctestexpectation 可以作为解决您的 异步调用 问题的工具。 - gaussblurinc
2个回答

10

您可以为通知添加期望:

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

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

waitForExpectationsWithTimeout(5, handler: nil)

但是我个人会将其分为两个测试。一个用于获取数据(使用存根进行测试),另一个用于发送通知。


3
"SUT" 是 "System Under Test" 的缩写。 - dasdom

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接