gpt4 book ai didi

ios - 在单元测试中处理 MainThread 执行

转载 作者:搜寻专家 更新时间:2023-10-31 21:46:50 24 4
gpt4 key购买 nike

我有一个在后台运行的函数,完成后它会在主线程中更新 UI。我注意到当代码到达对主线程的调用时单元测试失败。我该如何纠正这个问题?

例如注意:long 描述了项目中的伪逻辑,不是确切的代码

在主代码中:

func getResponse(identifier : String, completion :(success :Bool)->){
// uses identifier to request data via api and on completion:
completion(status: true)
}

testObject.getResponse(wantedValue){(success) in
if status == true {
dispatch_async(dispatch_get_main_queue()){
self.presentViewController(alertController, animated: true, completion: nil)

}
}
}

在单元测试中

func testGetResponse(){
var testObject = TestObject()
var expectation = self.self.expectationWithDescription("Response recieved")

testObject.getResponse(wantedValue){(success) in
expectation.fulfill()
}

self.waitForExpectationsWithTimeout(10) { (error) in
XCTAssertTrue(testViewController.presentedViewController as? CustomViewController)
}
}

这似乎是一个潜在的僵局,但我不确定如何解决它。

最佳答案

waitForExpectationsWithTimeout 也是您的异步​​函数未被调用或未正确完成(因此未调用 fulfill() 方法)情况下的回退方法。

尝试检查错误对象。

我建议在执行 fullfill() 调用之前进行验证。

请参阅以下 Swift 3 示例代码,了解如何使用 fullfill 和 waitForExpectationsWithTimeout。

func testGetResponse(){

var testObject = TestObject()
var validationExpectation = expectation(description: "Response received")

testObject.getResponse(wantedValue){(success) in
// Do your validation
validationExpectation.fulfill()
// Test succeeded
}

waitForExpectationsWithTimeout(60) { (error) in
if let error = error {
// Test failed
XCTFail("Error: \(error.localizedDescription)")
}
}
}

关于ios - 在单元测试中处理 MainThread 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44931458/

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