作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以,我有一个看起来像这样的类型:
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)
}
}
{
"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/
所以,我有一个看起来像这样的类型: struct Identifier { let string: String } extension Identifier: Decodable {
我是一名优秀的程序员,十分优秀!