[英]How to test method that runs async on main thread?
我只有一個方法:
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
//
}
您的方法必須有一個完成塊。 然后你可以使用一個Expectation
對象
let urlExpectation = expectation(description: "GET \(url)")
let process = PresentableProcess(title: "title")
sut.update(with: process) {
XCTAssertEqualWithAccuracy(sut.preferredContentSize, 95, accuracy: 10)
urlExpectation.fulfill()
}
或者為了避免添加完成塊,您可以創建一個協議,其中包含一個在設置結束時調用的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.