繁体   English   中英

如何测试在主线程上运行异步的方法?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM