3

I'm trying to write some unit tests and need a way to make a dummy version of an object that is mappable. For example:

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

Usually this is returned from an Alamofire call, but how would I manually create one and manually pass in an empty JSON string? Any advice on this would be greatly appreciated! Thanks!

Kex
  • 8,023
  • 9
  • 56
  • 129

2 Answers2

0

The object mapper defines an init function for your classes that allows you to pass a JSON dictionary object. In your test init a JSON object from a string and use that:

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.
    }
}

In my case I'm using this in a QuickSpec and importing SwiftyJSON, but should work in regular XCTest cases.

davidethell
  • 11,708
  • 6
  • 43
  • 63
0

You can simply use the functions written in Mappable.swift that your class implements

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

Inside these functions you will find this code:

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

So theoretically you can pass whatever data you want through these functions to test the mapping.

Khaled Annajar
  • 15,542
  • 5
  • 34
  • 45