[英]Test request body with OHHTTPStubs in Swift
I'm trying to test the request body sent captured with OHHTTPStubs but it seems buggy returning because the request.httpBody
is nil
. 我正在尝试测试用OHHTTPStubs捕获的请求体,但是因为request.httpBody
是nil
它似乎有问题。
I found this info about this problem Testing for the request body in your stubs . 我发现了有关此问题的此信息测试存根中的请求正文 。 But I'm pretty new in iOS development and don't know how to access to OHHTTPStubs_HTTPBody
in Swift. 但我在iOS开发方面很新,不知道如何在Swift中访问OHHTTPStubs_HTTPBody
。 How can I do this? 我怎样才能做到这一点?
I guess rough equivalent in Swift will be following: 我猜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"
}
}
So, more precisely, you can access OHHTTPStubs_HTTPBody
by calling ohhttpStubs_HTTPBody()
method inside OHHTTPStubsTestBlock
. 所以,更确切地说,您可以访问OHHTTPStubs_HTTPBody
通过调用ohhttpStubs_HTTPBody()
内的方法OHHTTPStubsTestBlock
。
What worked for me is the following: 对我有用的是:
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()
}
}
Credits to this person for converting InputStrem to Data: Reading an InputStream into a Data object 将此InputStrem转换为Data的此人的信用:将InputStream 读入Data对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.