所以,我有一个看起来像这样的类型:
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
的单元测试?
'1'
。所以,我想答案是:只需创建一个包装类型。 ¯\ _(ツ)_ /¯