我正在尝试使用 OHHTTPStubs 和 Quick/Nimble 测试 Alamofire 请求存根响应。但是 Alamofire 不处理响应,因此我无法测试结果。
我目前的测试代码是:
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.host == "authenticate.com"}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
let obj = ["status": "ok", "data": "something"]
return OHHTTPStubsResponse(JSONObject: obj, statusCode:200, headers:nil)
})
let gitdoRepository: GitdoRepository = GitdoRepository()
waitUntil(timeout: 2, action: { (done) -> Void in
gitdoRepository.authenticate("http://authenticate.com", completion: { (error) -> () in
expect(error).toNot(beNil())
})
NSThread.sleepForTimeInterval(2)
done()
})
我在存根闭包中添加了一个断点,以确保 Alamofire 执行请求并调用闭包。然而,客户端的响应闭包永远不会被调用,因此测试不会成功运行。这是验证方法:
func authenticate(authenticationUrl: String, completion: (error: OauthError?) -> ()) {
Alamofire.request(.POST, authenticationUrl).responseJSON { (request: NSURLRequest?, response: NSHTTPURLResponse?, object: AnyObject?, error: NSError?) -> Void in
if let error = error {
completion(error: .HTTPError(error))
}
else if let object = object {
if let oauth = self.oauthParser(object) {
self.oauth = oauth
completion(error: nil)
}
else {
completion(error: .UnparseableCredentials)
}
}
else {
completion(error: .ResponseWithoutCredentials)
}
}
}
我对 Alamofire 做错了什么吗?提前致谢