【问题标题】:Manually mapping an object using AlamoFireObjectMapper使用 AlamoFireObjectMapper 手动映射对象
【发布时间】:2016-10-22 12:37:24
【问题描述】:

我正在尝试编写一些单元测试,并且需要一种方法来制作可映射对象的虚拟版本。例如:

class MyClassJsonResponse: Mappable {

    var status: String?
    var response: String?
    var errorCode: SAErrorCode?

    init() {

    }

    required init?(_ map: Map) {

    }

    func mapping(map: Map) {
        status <- map["status"]
        response <- map["response"]
        errorCode <- (map["error_code"], SAErrorCodeTransform())
    }
}

通常这是从 Alamofire 调用返回的,但我如何手动创建一个并手动传入一个空的 JSON 字符串?对此的任何建议将不胜感激!谢谢!

【问题讨论】:

  • 你有没有找到从 Map 类创建对象然后在 init(map: Map) 中使用它的方法?

标签: swift alamofire objectmapper


【解决方案1】:

对象映射器为您的类定义了一个 init 函数,允许您传递 JSON 字典对象。在您的测试中,从字符串中初始化一个 JSON 对象并使用它:

let json = JSON.parse("{}")
if let _json = json.dictionaryObject {
    if let someObject = SomeObject(JSON: _json) {
        // Some assertions here
    }
    else {
        // Some assertions here about failure to map object, etc.
    }
}

在我的情况下,我在 QuickSpec 中使用它并导入 SwiftyJSON,但应该可以在常规 XCTest 案例中使用。

【讨论】:

    【解决方案2】:

    您可以简单地使用您的类实现的用 Mappable.swift 编写的函数

    public init?(JSON: [String: Any], context: MapContext? = nil)
    public init?(JSONString: String, context: MapContext? = nil)
    

    在这些函数中,您会找到以下代码:

    if let obj: Self = Mapper(context: context).map(JSON: JSON) {...}
    

    所以理论上你可以通过这些函数传递你想要的任何数据来测试映射。

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多