Test-Driven Development in Swift by Gio Lodi

Test-Driven Development in Swift by Gio Lodi

Author:Gio Lodi
Language: eng
Format: epub
ISBN: 9781484270028
Publisher: Apress


© Gio Lodi 2021

G. LodiTest-Driven Development in Swifthttps://doi.org/10.1007/978-1-4842-7002-8_9

9. Testing JSON Decoding

Gio Lodi1

(1)Mount Martha, VIC, Australia

How do you use tests to drive writing logic to decode JSON data into a model object?

By feeding the tests a predefined JSON input and verify the decoding produces a value matching it.

Swift’s Decodable protocol offers a type-safe way to describe how to transform Data, such as a JSON in the body of an HTTP response, into an object or value type. With Decodable doing most of the heavy lifting, is it worth using tests to drive the implementation of JSON decoding logic?

When the JSON object has keys and values with names and types that map directly to Swift, there is no real logic you need to write to decode it. In such a case, you may feel comfortable writing the source code directly, without the help of a unit test. If the JSON object is elaborate or if you want to decode it into a Swift type with a different structure, then a test will help you along the way.

Choosing whether to deploy TDD to implement JSON decoding logic is a matter of tradeoffs. Is the extra time you’re spending writing the test worth the feedback it gives you? Once the test is in place, will it guard against regression that may otherwise go unnoticed?

To answer those questions, you first need to know how to write this kind of tests. In this chapter, we’ll explore two different techniques to write tests for JSON decoding and reflect further on the return on investment of applying TDD to this part of the app’s implementation.

We’re moving along steadily in making our app fetch the menu from a remote API. In the previous chapters, we built the view part of this new functionality. It’s now time to take one step further down the stack, coding the conversion from the raw Data a network request would return into the MenuItem domain model.

Swift provides a convenient way to decode Data into a different type via the Decodable protocol. Our job is to conform MenuItem to it and verify the decoding is successful.

As part of your application development agreement with Alberto, you’re also building his backend service. You chose to use a REST API that returns a JSON menu in the following form:1[

{

"name": "spaghetti carbonara",

"category": "pasta",

"spicy": false

},

{

"name": "penne all'arrabbiata",

"category": "pasta",

"spicy": true

}

]



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.