我正在快速工作,我想刷新一个页面,所以我使用通知发送它,我在一个 ViewController 中发布通知并在另一个 ViewController 中添加观察者,它工作得很好。我想要做的是 swift 向它添加单元测试。我检查了很多网站,但无法做到。我是 swift 的新手,不知道从哪里开始。
基本上工作是,当我单击按钮时发布通知,并在加载下一个 View Controller 时添加通知观察器。
如何进行单元测试
提前致谢
编辑: 代码
NSNotificationCenter.defaultCenter().postNotificationName("notificationName", object: nil)
并将观察者添加为
NSNotificationCenter.defaultCenter().addObserver(self, selector: "vvv:",name:"notificationName", object: nil)
最佳答案
XCTest
有一个专门用于测试通知的类:XCTNSNotificationExpectation
.您创建了这些期望之一,并在收到通知时实现了。你会像这样使用它:
// MyClass.swift
extension Notification.Name {
static var MyNotification = Notification.Name("com.MyCompany.MyApp.MyNotification")
}
class MyClass {
func sendNotification() {
NotificationCenter.default.post(name: .MyNotification,
object: self,
userInfo: nil)
}
}
// MyClassTests.swift
class MyClassTests: XCTestCase {
let classUnderTest = MyClass()
func testNotification() {
let notificationExpectation = expectation(forNotification: .MyNotification,
object: classUnderTest,
handler: nil)
classUnderTest.sendNotification()
waitForExpectations(timeout: 5, handler: nil)
}
}
XCTestCase
的 expectation(forNotification:object:handler:)
是创建 XCTNSNotificationExpectation
实例的便捷方法,但为了获得更多控制,您可以实例化一个并自行配置。参见 the docs .
关于ios - 如何为 NSNotification 编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28292685/