在Swift中使用OHHTTPStubs测试请求体

时间:2017-05-20 11:16:21

标签: ios swift ohhttpstubs

我正在尝试测试使用OHHTTPStubs捕获的请求体,但它看起来似乎有问题,因为                 request.httpBodynil

我发现了有关此问题Testing for the request body in your stubs的此信息。但我在iOS开发方面很新,不知道如何在Swift中访问OHHTTPStubs_HTTPBody。我怎么能这样做?

2 个答案:

答案 0 :(得分:8)

我想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

答案 1 :(得分:0)

对我有用的是:

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转换为数据的信用:http://jsfiddle.net/eLmmA/1/