使用SingleValueDecodingContainer对可解码的单元测试一致性

问题描述 投票:3回答:1

所以,我有一个看起来像这样的类型:

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

这种类型的要点是,如果我有看起来像这样的JSON:

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

...它会自动进行序列化为正确的类型,而无需花费太多精力。但是,我无法在不创建包装类型的情况下对此一致性进行单元测试Decodable

我想做的是这样的:

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

但是显然,这不起作用,因为"1"不是有效的JSON。

是否可以在不创建包装类型并将数据更改为有效JSON的情况下编写符合Decodable的单元测试?

swift unit-testing codable decodable
1个回答
0
投票
[我放弃了在不创建包装类型的情况下放弃尝试实现这一点的假设,因为要解码一个以JSON开头的无效JSON字符串非常困难(在我的示例中为'1'

所以,我想答案是:只需创建一个包装类型。 ¯\ _(ツ)_ /¯

© www.soinside.com 2019 - 2024. All rights reserved.