1

试图使以下测试正常工作。它永远不会进入完成块,而是在 30 秒后超时。该请求似乎从未提出过,因为我在查尔斯身上看不到它。

func testAsynchronousURLConnection() {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")!
    let exp = expectation(description: "Async request")

    var urlRequest = URLRequest(url: url)

    urlRequest.httpMethod = "GET"
    urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
        XCTAssertNotNil(data, "data should not be nil")
        XCTAssertNil(error, "error should be nil")
        exp.fulfill()
    }

   task.resume()

    waitForExpectations(timeout: 30) { error in
        if let error = error {
            print("Error: \(error)")
        }
    }
}

测试失败并出现以下错误:

异步等待失败:超过 30 秒的超时且未实现预期:“异步请求”

我哪里错了?

4

0 回答 0