This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.
Testing custom Codable implementations
Discover page 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.

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.