gpt4 book ai didi

swift - API 违规 - 多次调用 -[XCTestExpectation fulfill]

转载 作者:IT王子 更新时间:2023-10-29 05:41:46 25 4
gpt4 key购买 nike

我正在用 Swift 编写我的第一个集成测试。

我正在尝试检查特定 url 中是否存在图像。

我想执行一个头部请求并检查响应的状态码。

我不断收到错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'API violation - multiple calls made to -[XCTestExpectation fulfill].

我试过让期望成为一个弱变量。

我有以下代码/测试:

func testAndroidImagesExist() {
weak var expectation: XCTestExpectation?
expectation = expectationForNotification(kBaoNotification_ManifestImportCompleted, object: nil) { (notification: NSNotification!) -> Bool in

let userInfo: NSDictionary = notification.userInfo!
var titles = userInfo.valueForKey("titles") as? NSArray
titles?.enumerateObjectsUsingBlock({ (t: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let title = t as NSDictionary

let titleLabel = title.valueForKey("title") as String
let parameters = title.valueForKey("parameters") as NSDictionary
let androidImageUrl = parameters.valueForKey("android_logo_url") as String
var androidRequest = NSMutableURLRequest(URL: NSURL(string: androidImageUrl)!)
androidRequest.HTTPMethod = "HEAD"
var androidResponse: NSURLResponse?
var androidData = NSURLConnection.sendSynchronousRequest(androidRequest, returningResponse: &androidResponse, error: nil)
var androidHttpResponse = androidResponse as? NSHTTPURLResponse

if androidHttpResponse != nil {
if androidHttpResponse!.statusCode == 404 {
XCTFail("Android image not found for title \(titleLabel)")
}
} else {
XCTFail("No response from android image for title \(titleLabel)")
}
})
expectation?.fulfill()
return true
}
waitForExpectationsWithTimeout(10, handler: { (error: NSError!) -> Void in
if (error != nil) {
XCTFail("Timeout error: \(error)")
}
})
}

有什么想法吗?

最佳答案

我建议处理多次发生的期望的最佳方式是在 fulfill 之后将期望变量设置为 nil。然后,后续调用将被忽略。

目标-C:

// Fulfill and remove. Subsequent messages to nil are ignored.
[multiEx fulfill];
multiEx = nil;`

swift :

// Fulfill and remove. Optional chaining ends execution on nil.
var multiEx:XCTestExpectation? = expectationWithDescription("multiEx")
...
multiEx?.fulfill()
multiEx = nil

关于swift - API 违规 - 多次调用 -[XCTestExpectation fulfill],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28189661/

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