Ios 如何测试在主线程上异步运行的方法?
我有一个简单的方法:Ios 如何测试在主线程上异步运行的方法?,ios,swift,unit-testing,Ios,Swift,Unit Testing,我有一个简单的方法: func update(with process: PresentableProcess) { presentableProcess = process if isViewLoaded { DispatchQueue.main.async { [weak self] in //do something on the main thread } } } 及其测试: func testPrefer
func update(with process: PresentableProcess) {
presentableProcess = process
if isViewLoaded {
DispatchQueue.main.async { [weak self] in
//do something on the main thread
}
}
}
及其测试:
func testPreferredContentSizeWhenTitleExist() {
let process = PresentableProcess(title: "title")
sut.update(with: process)
XCTAssertEqualWithAccuracy(sut.preferredContentSize, 95, accuracy: 10)
}
它不工作,因为它在主线程上运行。我希望避免在
update(with)
中添加完成块以通过测试。恐怕您需要使用完成块。要测试异步函数,请使用期望值
let expectation = expectation(description: "expectation")
doStuffWithCompletion() {
expectation.fulfill()
}
waitForExpectations(timeout: 10) { error in
//
}
您的方法必须有一个完成块。 然后您可以使用
期望
对象
let urlExpectation = expectation(description: "GET \(url)")
let process = PresentableProcess(title: "title")
sut.update(with: process) {
XCTAssertEqualWithAccuracy(sut.preferredContentSize, 95, accuracy: 10)
urlExpectation.fulfill()
}
或者,为了避免添加完成块,可以使用在安装程序结束时调用的方法创建协议