Weekly Swift articles, podcasts and tips by John Sundell.

Testing custom Codable implementations

Published on 13 May 2019
Basics article available: Codable

Here'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.