使用AlamoFireObjectMapper手动映射对象

时间:2016-06-21 05:38:54

标签: swift alamofire objectmapper

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

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字符串?任何有关这方面的建议将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:0)

对象映射器为您的类定义一个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情况下工作。

答案 1 :(得分:0)

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

Carseats$High <- factor(ifelse(Carseats$Sales <= 8, "No", "Yes"))

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

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

因此,从理论上讲,您可以通过这些函数传递所需的任何数据来测试映射。