当我运行应用程序时,到达 Alamofire 响应块没有问题。当使用 OHHTTPStubs 运行测试和模拟响应时,两个存根块(请求和响应)都会被调用,但 Alamofire 响应块永远不会被调用,因此测试失败。用 URLRequest 尝试了完全相同的存根,响应块被称为没有问题。
api类:
private static var config: URLSessionConfiguration?
private static var session: SessionManager?
static var instance = getInstance()
private static func getInstance() -> Api {
let api = self.init()
return api
}
private init() {
Api.config = URLSession.shared.configuration
var headers = SessionManager.defaultHTTPHeaders
headers.removeValue(forKey: "User-Agent")
headers["User-Agent"] = APP_VERSION
Api.config?.httpAdditionalHeaders = headers
Api.session = SessionManager(configuration: Api.config!)
}
func requestFunction(_ path: String) {
let req = Api.session!.request("\(apiUrl())\(path)", method: .get, parameters: request.toJSON()).response(completionHandler: completionHandler)
}
测试:
func test() {
stub(condition: { (request) -> Bool in
return true
}) { (request) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(
jsonObject: self.usageResponse,
statusCode: 200,
headers: ["Content-Type":"application/json"]
)
}
let semaphore = DispatchSemaphore.init(value: 0)
Api.instance.requestFunction(path, { (_, _) in
semaphore.signal()
})
let timeout = DispatchTime.now() + DispatchTimeInterval.seconds(300)
if semaphore.wait(timeout: timeout) == DispatchTimeoutResult.timedOut {
XCTFail("semaphore not reached")
}
}
信号量永远达不到。但是,如果我不调用 Alamofire 而不是这样做,那么信号量就没有问题了:
do {
let request = try URLRequest.init(url: "www.w.com", method: .post)
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let task = session.dataTask(with: request) { (_, _, _) in
semaphore.signal()
}
task.resume()
} catch {
}