Testing custom Codable implementations
Basics article available: CodableHere's a very simple way to test custom Codable
implementations — by just encoding and then decoding a value, and then verifying that the initial value and the decoded one are equal. Doesn't test edge cases, but it's a good start:
class UserTests: XCTestCase {
func testCoding() throws {
// Creating an instance of the Codable type that
// we want to test:
let user = User(
id: 7,
name: "John",
notes: [
Note(string: "Swift is awesome!")
]
)
// Encoding the instance into Data, then immediately
// decoding that data back into a new instance:
let data = try user.encoded()
let decodedUser = try data.decoded() as User
// Asserting that the two instances are equal:
XCTAssertEqual(user, decodedUser)
}
}
The above encoded
and decoded
convenience methods are part of the Codextended library.
Support Swift by Sundell by checking out this sponsor:

Raycast: Take the macOS Spotlight experience to the next level: Create Jira issues, manage GitHub pull requests and control other tools with a few keystrokes. Easily automate every-day tasks and boost your developer productivity by downloading Raycast for free.