Search code examples
swiftunit-testingcodabledecodable

Unit testing conformance to Decodable using a SingleValueDecodingContainer


So, I have a type which looks like this:

struct Identifier {
    let string: String
}

extension Identifier: Decodable {
    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        string = try container.decode(String.self)
    }
}

The point with this type is if I have JSON that looks like this:

{
    "identifier": "abc123",
    // more properties ...
}

... it will automatically be serialized to the correct type without much effort. However, I'm having trouble unit testing this conformance to Decodable without creating a wrapping type.

What I want to do is something like this:

func testDecodableInit() {
    let identifier = try! JSONDecoder().decode(Identifier.self, from: "1".data(using: .utf8)!)
    XCTAssertEqual(identifier.string, "1")
}

But obviously this doesn't work because "1" is not valid JSON.

Is it possible to write a unit test for this conformance to Decodable without creating a wrapping type and changing the data to valid JSON?


Solution

  • I gave up trying to accomplish this without creating a wrapping type on the assumption that it's very hard to decode a string that isn't valid JSON to begin with ('1' in my example).

    So, I guess, the answer is: just create a wrapping type. ¯\_(ツ)_/¯