我正在尝试测试用OHHTTPStubs捕获的请求体,但是返回似乎是错误的,因为request.httpBody是nil。
我找到了关于这个问题的信息,测试存根中的请求主体。但是我在iOS开发方面还很新,不知道如何在Swift中访问OHHTTPStubs_HTTPBody。我该怎么做?
发布于 2017-05-23 09:16:30
我想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。
发布于 2017-07-23 04:28:43
对我有用的是以下几点:
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转换为数据而归功于此人员:将InputStream读入数据对象
https://stackoverflow.com/questions/44085214
复制相似问题