出于测试目的,我有以下测试功能:
func test_wait() {
var string: String?
DispatchQueue.main.async {
string = "set"
print("string set")
}
let notNilPredicate = NSPredicate(format: "self != nil")
let notNilExpectation = expectation(for: notNilPredicate, evaluatedWith: string)
print("start waiting")
let waitResult = XCTWaiter.wait(for: [notNilExpectation], timeout: 5)
XCTAssert(waitResult == .completed, "wait for notNilExpectation failed with result (waitResult)")
}
此测试失败
等待结果为.timedOut
,日志为
start waiting
string set
… : XCTAssertTrue failed - wait for notNilExpectation failed with result XCTWaiterResult(rawValue: 2)
Interrupting test
虽然设置了var string
,但我不明白为什么等待失败
但是,当我输出注释DispatchQueue.main.async
时,即当我同步执行其块时,测试成功。然后日志为
string set
start waiting
Test Case '-[ShopEasyTests.CoreDataCloudKitContainerTest test_wait]' passed (1.087 seconds).
据我所知,异步版本的测试函数也应该可以工作
怎么了?
它是谓词(以及捕获的语义)。您认为您正在将对string
的引用交给谓词求值,但事实并非如此;你只是通过了nil
,而nil
不会很快神奇地成为非nil
。为了减少混淆,请重写为
let notNilPredicate = NSPredicate {_,_ in string != nil }
let notNilExpectation = expectation(for: notNilPredicate, evaluatedWith: nil)