gpt4 book ai didi

swift - 使用 AlamoFireObjectMapper 手动映射对象

转载 作者:可可西里 更新时间:2023-10-31 23:35:56 25 4
gpt4 key购买 nike

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

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 字符串?对此的任何建议将不胜感激!谢谢!

最佳答案

对象映射器为您的类定义了一个 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 案例中工作。

关于swift - 使用 AlamoFireObjectMapper 手动映射对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37936360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com