gpt4 book ai didi

ios - XCTest POST API性能测试

转载 作者:行者123 更新时间:2023-11-30 12:19:12 25 4
gpt4 key购买 nike

我正在为我的 iOS swift 项目实现单元测试。我想对我的项目中的 POST API 实现性能测试,但我不知道如何实现该 POST API。我已经测试了 GET API,它给了我想要的结果。

这是我想要实现的代码

func testPerfromancePOSTAPI() {
let session = URLSession.shared
var request = URLRequest(url: MY_URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: MY_SERVICE_PARA, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
self.measure {
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print("response JSON = \(json)")
}
} catch let error {
XCTFail("Expectation Failed with error: %@", file: error as! StaticString);
}
})
task.resume()
}
}

当我运行此测试时,它成功通过,但没有打印响应 JSON,也没有给出错误并显示“时间 0.0000 秒(161% STDEV)”,而在 postman 中运行相同的 API 需要几秒。请检查并帮我解决这个问题。

最佳答案

尝试按如下方式更改您的代码

 func testPerfromancePOSTAPI() {
let session = URLSession.shared
var request = URLRequest(url: MY_URL)
let expectations = expectation(description: "POST")
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: MY_SERVICE_PARA, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
self.measure {
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print("response JSON = \(json)") expectations.fulfill()
}
} catch let error {
XCTFail("Expectation Failed with error: %@", file: error as! StaticString);
}
})
task.resume()
self.waitForExpectations(timeout: 10) { (error) in
if let error = error {
XCTFail("Error: \(error.localizedDescription)")
}
}

}
}

如果您仍然没有收到任何响应,请将超时值更改为更高的值。

关于ios - XCTest POST API性能测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45004953/

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