Art*_*nko 5 unit-testing xctest swift xctestexpectation
我正在用Swift编写一个XCTest单元测试。这个想法是在某种情况下不能调用回调。
所以我要做的是
func testThatCallbackIsNotFired() {
let expectation = expectationWithDescription("A callback is fired")
// configure an async operation
asyncOperation.run() { (_) -> () in
expectation.fulfill() // if this happens, the test must fail
}
waitForExpectationsWithTimeout(1) { (error: NSError?) -> Void in
// here I expect error to be not nil,
// which would signalize that expectation is not fulfilled,
// which is what I expect, because callback mustn't be called
XCTAssert(error != nil, "A callback mustn't be fired")
}
}
Run Code Online (Sandbox Code Playgroud)
当回调被调用时,一切正常:它失败并显示一条消息“不能触发回调”,这正是我所需要的。
但是如果期望没有得到满足,它就会失败并说
异步等待失败:超过 1 秒超时,未满足预期:“回调已触发”。
由于未满足的期望是我所需要的,因此我不希望测试失败。
你有什么建议我可以做些什么来避免这种情况?或者,也许,我可以以不同的方式达到我的目标?谢谢。
isInverted在这篇文章中使用像https://www.swiftbysundell.com/posts/unit-testing-asynchronous-swift-code
class DebouncerTests: XCTestCase {
func testPreviousClosureCancelled() {
let debouncer = Debouncer(delay: 0.25)
// Expectation for the closure we'e expecting to be cancelled
let cancelExpectation = expectation(description: "Cancel")
cancelExpectation.isInverted = true
// Expectation for the closure we're expecting to be completed
let completedExpectation = expectation(description: "Completed")
debouncer.schedule {
cancelExpectation.fulfill()
}
// When we schedule a new closure, the previous one should be cancelled
debouncer.schedule {
completedExpectation.fulfill()
}
// We add an extra 0.05 seconds to reduce the risk for flakiness
waitForExpectations(timeout: 0.3, handler: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题,并且我很恼火的是您无法使用处理程序来覆盖 waitForExpectationsWithTimeout 的超时失败。这是我解决它的方法(Swift 2 语法):
func testThatCallbackIsNotFired() {
expectationForPredicate(NSPredicate{(_, _) in
struct Holder {static let startTime = CACurrentMediaTime()}
if checkSomehowThatCallbackFired() {
XCTFail("Callback fired when it shouldn't have.")
return true
}
return Holder.startTime.distanceTo(CACurrentMediaTime()) > 1.0 // or however long you want to wait
}, evaluatedWithObject: self, handler: nil)
waitForExpectationsWithTimeout(2.0 /*longer than wait time above*/, handler: nil)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1838 次 |
| 最近记录: |