((注意-我正在为macOS开发,所以请...针对iOS的建议不会对我有帮助)
我正在尝试做的事情:我有一个在后台线程上执行简短任务的应用程序组件,然后,如果满足某些条件,则在主线程上异步发出通知。
我正在为上述应用程序组件编写单元测试,并简单地想要检查该通知是否确实发送。我的测试必须能够等待一秒钟左右,以便在执行断言之前给通知时间到达其订阅者/观察者。
编辑-我希望能够在测试中测试两种情况:这都是正常情况,具体取决于应用程序的状态。
通知已发送。
未发送通知。
阅读了数小时的文档和代码示例后,我不明白如何以期望的方式实现这一目标。
我只想在测试中等待一秒钟。真的这么复杂吗?
这里是需要测试的应用程序组件,以及其单元测试:
在下面的代码中,我将Expectation.fulfill()放在哪里?
class ComponentBeingTested {
func methodBeingTested() {
doSomeWork()
if certainConditionsAreMet {
DispatchQueue.main.async {sendOutNotification()}
}
}
}
...
class UnitTestForComponentBeingTested: XCTestCase {
let objectBeingTested = ComponentBeingTested()
func testMethodBeingTested() {
let expectation = self.expectation(description: "Notification was sent")
// Call the code being tested
objectBeingTested.methodBeingTested()
// How do I do this with expectations ??? Where does expectation.fulfill() go ?
waitForOneSecond()
XCTAssertTrue(notificationSent) // Assume the value of notificationSent is available
}
}
这里是一种方法
func testMethodBeingTested() {
// create expectation
let expectation = self.expectation(description: "Notification was sent")
// set expectation condition
var notificationSent = false
let observer = NotificationCenter.default
.addObserver(forName: _Your_Notification_Name, object: nil, queue: nil) { _ in
notificationSent = true
expectation.fulfill()
}
// Call the code being tested
objectBeingTested.methodBeingTested()
// wait for expectation
self.wait(for: [expectation], timeout: 5)
XCTAssertTrue(notificationSent)
}