【问题标题】:Creating a Alamofire Response for a test为测试创建 Alamofire 响应
【发布时间】:2016-01-11 18:55:56
【问题描述】:

我在我的 iOS 应用程序中使用 Alamofire 进行 API 调用。我试图在测试中存根这些数据,我尝试过 Mockingjay 和 OHHTTPStubs 但都不起作用,所以我现在试图存根收到的响应。

我需要使用可以传递给其他方法的虚拟数据创建一个响应。这是 Alamofire 中 Response 对象的初始化程序:

public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>)

但是我无法确定如何创建此对象,因为我无法创建结果。以下是 Alamofire 的一些结果类:

public enum Result<Value, Error: ErrorType> {
    case Success(Value)
    case Failure(Error)

    /// Returns `true` if the result is a success, `false` otherwise.
    public var isSuccess: Bool {
        switch self {
        case .Success:
            return true
        case .Failure:
            return false
        }
    }

    /// Returns `true` if the result is a failure, `false` otherwise.
    public var isFailure: Bool {
        return !isSuccess
    }

    /// Returns the associated value if the result is a success, `nil` otherwise.
    public var value: Value? {
        switch self {
        case .Success(let value):
            return value
        case .Failure:
            return nil
        }
    }

    /// Returns the associated error value if the result is a failure, `nil` otherwise.
    public var error: Error? {
        switch self {
        case .Success:
            return nil
        case .Failure(let error):
            return error
        }
    }
}

我似乎不知道如何将结果传递给带有值的响应对象,以表示 API 响应。

我想我对枚举以及它们如何在其中也包含变量感到困惑。

谁能帮我做出回应?

谢谢。

已回答

感谢您的回答...这是使用 json 响应创建整个响应的方法

let london : NSDictionary = ["name" : "london", "latitude" : 23.00, "longitude" : 0.0, "id" : "london_gb"]
                let paris : NSDictionary = ["name" : "paris", "latitude" : 30.00, "longitude" : -1.0, "id" : "paris_fr"]
                let locations = NSArray(array: [london, paris])
                let result = Result<AnyObject, NSError>.Success(locations)

                var response = Response(request: NSURLRequest(), response: NSHTTPURLResponse(), data: NSData(), result: result)

【问题讨论】:

    标签: ios swift enums nsurl alamofire


    【解决方案1】:

    以@66o 的答案为基础,但更新到 Swift 4 / Alamofire 4

    import Alamofire
    ...
    
    let result = Result<Any>.success("Hello")
    let dataResponse = DataResponse(request: nil, response: nil, data: nil, result: result)
    

    【讨论】:

      【解决方案2】:

      请看下面的例子:

      let result = Result<String, NSError>.Success("Hello")
      
      result.isSuccess // prints true
      result.value // prints "Hello"
      

      希望有帮助

      【讨论】:

      • 非常感谢!这非常有效..将用完整的回复更新我的问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2017-04-21
      相关资源
      最近更新 更多