如果 iOS 应用程序有自己的请求,OHHTTPStubs 不会模拟请求?
如果 App 在测试运行之前发出任何 Alamofire 请求,OHHTTPStubs 将不会在单元测试中模拟任何请求
OHHTTPStubs 4.3.0 with swift support
Alamofire 2.0.2
测试文件- 按预期工作
stub(isHost("httpbin.org")) { _ in
let stubData = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding)
return OHHTTPStubsResponse(data: stubData!, statusCode:200, headers:nil)
}
print("@@Start")
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.responseString() { request, response, data in
print(data)
}
但是,一旦将以下内容添加到 AppDelegate.swift,它就不再起作用,而是向服务发出实际的 HTTP 请求
Alamofire.request(.GET, "http://httpbin.org/get")
.responseString() { request, response, data in
print(data)
}
留给后代的原始问题
更新:我在一个干净的项目中再次尝试,它按预期工作,所以一定有其他事情发生。
在 swift 2.0 的最新升级中,OHHTTPStubs 并没有对请求进行存根处理,而是通过并实时调用它们。
我在单元测试中设置了一个简短的示例,但它仍然通过。我错过了什么?
import Foundation
import Quick
import Nimble
import Alamofire
import OHHTTPStubs
class RequestsSpec: QuickSpec {
var data:Result<String>? = nil
override func spec() {
describe("the request") {
it("needs to make a request") {
stub(isHost("httpbin.org")) { _ in
let stubData = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding)
return OHHTTPStubsResponse(data: stubData!, statusCode:200, headers:nil)
}
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.responseString() { request, response, data in
print(request)
print(response)
print(data)
print(data.value)
self.data = data
}
expect(self.data).toEventuallyNot(beNil(), timeout: 3)
}
}
}
我明白了
Optional(<NSMutableURLRequest: 0x7f91598e22e0> { URL: http://httpbin.org/get?foo=bar })
Optional(<NSHTTPURLResponse: 0x7f915da8c220> { URL: http://httpbin.org/get?foo=bar } { status code: 200, headers {
"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 364;
"Content-Type" = "application/json";
Date = "Thu, 01 Oct 2015 04:19:42 GMT";
Server = nginx;
} })
Optional("{\n \"args\": {\n \"foo\": \"bar\"\n }, \n \"headers\": {\n \"Accept\": \"*/*\", \n \"Accept-Encoding\": \"gzip;q=1.0,compress;q=0.5\", \n \"Accept-Language\": \"en-US;q=1.0\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"ios-consumer-app/com.dante.ouli2 (28; OS Version 9.0 (Build 13A340))\"\n }, \n \"url\": \"http://httpbin.org/get?foo=bar\"\n}\n")
而不是 Hello World!
我尝试使用 NSURLSession 发出请求,并且 OHHTTPStubs 正常工作。OHHTTPStubs/Alamofire 交互似乎有问题?
let url = NSURL(string: "http://httpbin.org/get")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
self.data2 = data
}
- 快速支持的 OHHTTPStubs 4.3.0
- 阿拉莫菲尔 2.0.2