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

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())
    }
}

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

最佳答案

对象映射器为类定义了一个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,但是应该在常规的XCEST案例中工作。

07-24 09:51
查看更多