ios - 为测试创建 Alamofire 响应

标签 ios swift enums nsurl alamofire

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

我需要创建一个包含虚拟数据的响应,我可以将其传递给我的其他方法。下面是 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)

最佳答案

看下面的例子:

let result = Result<String, NSError>.Success("Hello")

result.isSuccess // prints true
result.value // prints "Hello"

希望对你有帮助

关于ios - 为测试创建 Alamofire 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33112578/

相关文章:

iOS - 在越狱设备上访问沙箱外的文件系统

C++:扩展枚举定义?

c++ - 在 C++ 中 : Is it possible to have a named enum be continued in a different file?

ios - 比例 View 约束

ios - 使用SegmentController让TableView消失,UIContainerView出现

objective-c - 如何在屏幕上显示 UIControl 的子类

ios - 在“Cirrious.MvvmCross.Plugins.DownloadCache.MvxFileDownloadCache/Timer”中找不到嵌套类型

swift - 类 RTCCVPixelBuffer 在两者中都实现,将使用两者之一。哪个是未定义的

swift - 无法转换类型 [(key :string, value :int)] to specified type Dictionary<String, Int>

java - 2 个相似的 java 枚举和一个方法决定应该从哪个枚举中选择值