在 Swift 中使用 OHHTTPStubs 测试请求正文

Posted

技术标签:

【中文标题】在 Swift 中使用 OHHTTPStubs 测试请求正文【英文标题】:Test request body with OHHTTPStubs in Swift 【发布时间】:2017-05-20 11:16:20 【问题描述】:

我正在尝试测试使用 OHHTTPStubs 捕获的发送请求正文,但返回似乎有问题,因为 request.httpBodynil

我找到了关于这个问题的信息Testing for the request body in your stubs。但我是 ios 开发的新手,不知道如何在 Swift 中访问 OHHTTPStubs_HTTPBody。我该怎么做?

【问题讨论】:

【参考方案1】:

我猜 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"
  

因此,更准确地说,您可以通过在OHHTTPStubsTestBlock 中调用ohhttpStubs_HTTPBody() 方法来访问OHHTTPStubs_HTTPBody

【讨论】:

从 Swift 3 开始有一个小的区别,因为请求是 URLRequest 并且 OHHTTPSubs 的扩展是为 NSURLRequest 编写的。这意味着您需要先对请求对象进行类型转换:let nsRequest = request as NSURLRequest,然后您可以使用nsRequest.ohhttpStubs_HTTPBody()【参考方案2】:

对我有用的是:

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 转换为数据:Reading an InputStream into a Data object

【讨论】:

以上是关于在 Swift 中使用 OHHTTPStubs 测试请求正文的主要内容,如果未能解决你的问题,请参考以下文章

未找到“OHHTTPStubs/OHHTTPStubs.h”文件

让 Alamofire 和 OHHTTPStubs 一起工作

OHHTTPStubs 不是存根主机?

使用 OHHTTPStubs 模拟时未达到 Alamofire 响应块

OHHTTPStubs 单元测试实现

iOS单元測试:Specta + Expecta + OCMock + OHHTTPStubs + KIF