Ios 如何编写单元测试以接收异步通知?
我使用完成处理程序调用rest web服务,如果成功,我将发送通知 问题是如何编写单元测试来断言在成功的情况下发送通知Ios 如何编写单元测试以接收异步通知?,ios,swift,nsnotificationcenter,xctest,nsnotification,Ios,Swift,Nsnotificationcenter,Xctest,Nsnotification,我使用完成处理程序调用rest web服务,如果成功,我将发送通知 问题是如何编写单元测试来断言在成功的情况下发送通知 任何帮助都将不胜感激。您可以添加对通知的期望: expectationForNotification("BlaBlaNotification", object: nil) { (notification) -> Bool in // call the method that fetches the data sut.fetchData() waitForExpec
任何帮助都将不胜感激。您可以添加对通知的期望:
expectationForNotification("BlaBlaNotification", object: nil) { (notification) -> Bool in
// call the method that fetches the data
sut.fetchData()
waitForExpectationsWithTimeout(5, handler: nil)
但我个人认为这是两个测试。一个用于获取数据(使用存根测试),另一个用于发送通知。这就是我测试通知的方式:
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)
}
例如,可以解决您的问题,因为
异步调用
sut
是被测系统的缩写。