Articles, podcasts and news about Swift development, by John Sundell.

Testing custom Codable implementations

Published on 13 May 2019
Discover page 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.

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.