我正在尝试测试使用 OHHTTPStubs 捕获的发送的请求正文,但由于
request.httpBody
是nil
.
我在你的存根中找到了关于这个问题测试请求正文的信息。但我是 iOS 开发的新手,不知道如何OHHTTPStubs_HTTPBody
在 Swift 中访问。我怎样才能做到这一点?
我正在尝试测试使用 OHHTTPStubs 捕获的发送的请求正文,但由于
request.httpBody
是nil
.
我在你的存根中找到了关于这个问题测试请求正文的信息。但我是 iOS 开发的新手,不知道如何OHHTTPStubs_HTTPBody
在 Swift 中访问。我怎样才能做到这一点?
我猜 Swift 中的大致等价物如下:
import OHHTTPStubs.NSURLRequest_HTTPBodyTesting
...
stub(isMethodPOST() && testBody()) { _ in
return OHHTTPStubsResponse(data: validLoginResponseData, statusCode:200, headers:nil)
}).name = "login"
public func testBody() -> OHHTTPStubsTestBlock {
return { req in
let body = req.ohhttpStubs_HTTPBody()
let bodyString = String.init(data: body, encoding: String.Encoding.utf8)
return bodyString == "user=foo&password=bar"
}
}
所以,更准确地说,你可以OHHTTPStubs_HTTPBody
通过调用ohhttpStubs_HTTPBody()
里面的方法来访问OHHTTPStubsTestBlock
。
对我有用的是以下内容:
func testYourStuff() {
let semaphore = DispatchSemaphore(value: 0)
stub(condition: isScheme(https)) { request in
if request.url!.host == "blah.com" && request.url!.path == "/blah/stuff" {
let data = Data(reading: request.httpBodyStream!)
let dict = Support.dataToDict(with: data)
// at this point of time you have your data to test
// for example dictionary as I have
XCTAssertTrue(...)
} else {
XCTFail()
}
// flag that we got inside of this block
semaphore.signal()
return OHHTTPStubsResponse(jsonObject: [:], statusCode:200, headers:nil)
}
// this code will be executed first,
// but we still need to wait till our stub code will be completed
CODE to make https request
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
}
// convert InputStream to Data
extension Data {
init(reading input: InputStream) {
self.init()
input.open()
let bufferSize = 1024
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
while input.hasBytesAvailable {
let read = input.read(buffer, maxLength: bufferSize)
self.append(buffer, count: read)
}
buffer.deallocate(capacity: bufferSize)
input.close()
}
}
归功于此人将 InputStrem 转换为 Data:将 InputStream读入 Data 对象