6

我正在尝试测试使用 OHHTTPStubs 捕获的发送的请求正文,但由于 request.httpBodynil.

我在你的存根中找到了关于这个问题测试请求正文的信息。但我是 iOS 开发的新手,不知道如何OHHTTPStubs_HTTPBody在 Swift 中访问。我怎样才能做到这一点?

4

2 回答 2

9

我猜 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-05-23T09:16:30.227 回答
1

对我有用的是以下内容:

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 对象

于 2017-07-23T04:28:43.530 回答