gpt4 book ai didi

swift - 使用 SingleValueDecodingContainer 对 Decodable 的一致性进行单元测试

转载 作者:行者123 更新时间:2023-12-04 18:23:11 26 4
gpt4 key购买 nike

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

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。

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

最佳答案

如果有人想知道如何使用包装类型创建测试。它看起来像这样;

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

我们的测试看起来像这样;
class IdentifierTests: XCTestCase {

func testStringValueDecodedSuccessfully() throws {
let decoder = JSONDecoder()
let data = Data("{\"value\": \"identifier-string\"}".utf8)
let container = try decoder.decode(Wrapper1.self, from: data)
XCTAssertEqual(container.identifierValue.string, "identifier-string")
}
}

private struct Wrapper: Decodable {

let identifierValue: Identifier

enum CodingKeys: String, CodingKey {
case value
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
identifierValue = try container.decode(Identifier.self, forKey: .value)
}
}

关于swift - 使用 SingleValueDecodingContainer 对 Decodable 的一致性进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50237898/

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