gpt4 book ai didi

swift - 如果 XCTestExpectation 出乎意料怎么办

转载 作者:搜寻专家 更新时间:2023-10-31 08:33:23 27 4
gpt4 key购买 nike

我正在用 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")
}
}

当回调被调用时,一切正常:它失败并显示消息“A callback mustn't be fired”,这正是我所需要的。

但是如果期望还没有实现,它就会失败并说

异步等待失败:超时超过 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)
}
}

关于swift - 如果 XCTestExpectation 出乎意料怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32807721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com