Share E-Book

Test-Driven Development in Swift, Second Edition Compile Better Code with Swift Testing and TDD (Gio Lodi)(Z-Library)

Author Gio Lodi

code
Language English

Leverage Swift to practice effective and efficient Test-Driven Development (TDD). Software testing and TDD are evergreen programming concepts—yet Swift developers haven’t widely adopted them. What’s needed is a clear roadmap to learn and adopt TDD in the Swift world. Apple has invested heavily in the Swift Testing library and Xcode’s testing infrastructure, making testing a first-class priority in their ecosystem. The tools are there. This book will show you how to wield them. TDD has much more to offer than catching bugs. With this book, you’ll learn a philosophy for building software. TDD helps you solve problems incrementally, writing only as much code as necessary. By decomposing big problems into small steps, you can move along at a fast pace, always making visible progress. Embark on the Test-Driven Development journey by building a real iOS application and picking up new techniques in each chapter. The book’s concepts will emerge as you figure out ways to use tests to drive the solutions to the problems of each chapter. You’ll be introduced to all the staples and advanced concepts of the craft, understand the trade-offs each technique offers, and review an iterative process of software development. In this fully revised edition, all code is updated to use Apple’s new Swift Testing framework, with networking rewritten using structured concurrency and UI refreshed to match the latest SwiftUI APIs and iOS 26 design, making it the ideal resource for developers embracing the latest computing and development tools. Test-Driven Development in Swift gives you the blueprint for a highly efficient way to make amazing apps. What You Will Learn: • Write tests that are easy to maintain • Manage and scale an ever-growing test suite • Build a testing vocabulary that transfers beyond Swift • See how Swift’s type system enhances the TDD flow of dynamic languages • Discover how compiler errors can provide the same helpful guidance as failing tests

Format PDF
Size 5.7 MB
14
Views
0
Downloads
0.00
Total Donations
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
Test-Driven Development in Swift Compile Better Code with Swift Testing and TDD — Second Edition — Gio Lodi
Page 2
Test-Driven Development in Swift Compile Better Code with Swift Testing and TDD Second Edition Gio Lodi
Page 3
Test-Driven Development in Swift: Compile Better Code with Swift Testing and TDD, Second Edition ISBN-13 (pbk): 979-8-8688-2636-8 ISBN-13 (electronic): 979-8-8688-2637-5 https://doi.org/10.1007/979-8-8688-2637-5 Copyright © 2026 by Gio Lodi This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Miriam Haidara Editorial Assistant: Marina Engler Cover designed by eStudioCalamar Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress. com/gp/services/source-code. If disposing of this product, please recycle the paper. Gio Lodi Melbourne, VIC, Australia
Page 4
For Finn and Olive, who keep teaching me how to be present and curious.
Page 5
(This page has no text content)
Page 6
(This page has no text content)
Page 7
(This page has no text content)
Page 8
(This page has no text content)
Page 9
(This page has no text content)
Page 10
(This page has no text content)
Page 11
xi About the Author Gio Lodi has spent the past 15 years writing tests. He began with full-stack web development before moving into iOS programming and, more recently, into mobile infrastructure engineering. Ruby on Rails introduced him to the TDD world, and he fell in love with the fast-paced feedback loop. Any big problem could be decomposed into smaller and smaller parts until it got to an achievable size. When Gio moved into the Apple ecosystem, he found its lack of testing tools disturbing. He began researching and experimenting with testing strategies and tooling, sharing his findings on his blog and in talks and workshops at various industry conferences.
Page 12
xiii About the Technical Reviewer Vishwesh Ravi Shrimali graduated from BITS Pilani in 2018, where he studied mechanical engineering. Currently, he is working at Mercedes-Benz R&D India as a tech lead. He has also authored multiple books on data science and AI. When he is not writing blogs or working on projects, he likes to go on long walks or play his acoustic guitar.   
Page 13
xv Acknowledgments This book wouldn’t have been possible were it not for the giants whose shoulders I stood on. Tallest among all is Kent Beck, whose “rediscovery” of Test-Driven Development (TDD) started the process, eventually bringing us here. Next to him are Michael Feathers, Martin Fowler, and Gary Bernhardt; their work instructed and inspired me. Standing on giants’ shoulders is a precarious predicament. Luckily, I had guardian angels that kept me from falling: my children motivated and helped me unplug; my wife patiently waited through all my “I just need five more minutes.” Many thanks to the team at Apress for taking a chance on me as a first-time author. In particular, thank you to Jessica Vakili: you’ve been patient and helpful. I owe a lot to Luca Ferrari and Mattia Toso. More than a decade ago, while attending Università degli Studi di Ferrara, they approached me to collaborate on a startup idea. We ended up using Ruby on Rails, which is how I stumbled upon Test-Driven Development. Also, thanks to Giulio Grillanda, Marco Bersani, and Matteo Bonora, who joined us and made the dream come true. You’ve all been incredible friends and supporters over the years. Since 2014, I’ve been calling Melbourne, Australia, my home. Here, I’ve been lucky to find a friendly and welcoming community of like-minded folks with whom to share and sharpen ideas. Thanks to Aron Bury, Audrey Tam, Matt Delves, Pete Goldsmith, Stew Gleadow, and the Itty Bitty Apps crew for all the conversations and support and for being good friends. Special thanks to Adam Johnson, Charlie Scheer, Martin Heroux, and Richard Moult for the feedback on my early drafts and to Samuele Fiorini for the initial encouragement.
Page 14
xvi I also want to thank Chris Toomey and Steph Viccari, who shared ideas on testing when hosting The Bike Shed podcast, which is also where I heard the beautiful “helpful pressure” analogy, and Ben Orenstein, from whom I learned about the Mystery Guest pattern. Thank you to all those who deserve to be here, but that, in my distraction, I forgot to mention. Echoing Lynne Truss in Eats, Shoots & Leaves, I’d like to thank the learned copy and technical editors who have attempted to sort out my writing and save me from embarrassment. Where faults obstinately remain, they are mine alone. Thank you to everyone who ever visited my blog, mokacoding.com. Your feedback and support keep fueling my work. Finally, thank you, dear reader. Thank you for picking up this book among many and sharing your valuable time with me. aCknowledgmenTs
Page 15
xvii A Gift for You Thank you for reading and finishing this book. Your time is valuable; I consider it a privilege that you decided to spend it with me. As a sign of my gratitude, I want to offer something in return: For extra content, snippets, and further reading recommendations, head over to https://tddinswift.com/gift. If you enjoyed this book, please consider sharing it with a friend and leaving a review on your favorite platform. This goes a long way to help the book spread. I hope we can continue the conversation about how to write clean code that works. Don’t hesitate to get in touch if you have any questions or to share your Test-Driven Development success story. Thanks, Gio
Page 16
xix A Note on Indentation and Method Names At the time of writing, there are no official Swift coding style guidelines. When it comes to indentation, the default in Xcode 26 is four spaces. On the other hand, the official Swift formatting tool, swift-format, uses two spaces. Two spaces is also the style used in the code samples in the Swift Testing documentation. In the interest of keeping code samples compact in the limited space of the printed edition, this book, too, uses two spaces. For the same reason, test and method names are at times overly succinct. The test name and description “payment ok shows confirmation alert” is less clear than “when payment is successful, configures alert ViewModel as confirmation,” but only the former fits in a single line in the printed edition.
Page 17
1© Gio Lodi 2026 G. Lodi, Test-Driven Development in Swift, https://doi.org/10.1007/979-8-8688-2637-5_1 CHAPTER 1 Why Test-Driven Development? What Is a Test? The Oxford English Dictionary defines the noun test as “a procedure intended to establish the quality, performance, or reliability of something, especially before it is taken into widespread use.” In the context of software development, we can adapt the definition to “a procedure intended to establish the software quality, performance, or reliability, especially before it is shipped to the users.” To test our software essentially means to run it and verify it behaves as desired. Take this “Hello, World!” script, for example: #!/usr/bin/env swift func main() { guard CommandLine.argc > 1 else { print("Hello, World!") return }
Page 18
2 print("Hello, \(CommandLine.arguments[1])!") } main() To test it, we could run it with no input, ./hello_world.swift, and check that it prints “Hello, World!” We could then run it with a specific input and verify it uses it in the salutation. Running ./hello_world.swift Ada should print “Hello, Ada!” In the same way, you can launch an iOS app in the Simulator and click through its user interface (UI) to check it behaves as you programmed it to. Or you can submit data using a form in a web application and then check that the database contains it. All the preceding examples share a trait: someone has to exercise the software and verify its behavior. They are manual tests. To consistently ship quality software on a schedule, manual testing is not enough. Manual Testing Is Inefficient We can manually test a little script like hello_world.swift thoroughly because of its narrow feature set, but real-world programs are not as simple. Even in the smallest application, there are many possible code paths, many permutations of inputs the code accepts, and steps a user can take within the system. To test them all manually would take a lot of time. Manual testing is costly as well as time consuming. Regardless of who performs the tests, whether it’s software or QA engineers, product owners, or a third-party firm, real people have salaries to be paid. They also need time off to rest, get sick, may forget things, and, inevitably, make mistakes. However, skipping testing to save time and money would be a terrible move. Chapter 1 Why test-Driven Development?
Page 19
3 If we don’t test our products before shipping them, the users will do it for us. That’s far from ideal. While we might celebrate discovering a bug, a user would get frustrated and possibly leave our product for a competitor. There must be a way to test our software to a high degree of confidence, fast, and without requiring humans to do all the work. Code That Checks Other Code Software developers write code to automate tasks that would otherwise be manual. Over the past decades, software has been “eating the world” as investor Marc Andreessen put it in a 2011 essay. People used to send signed documents with a fax machine, carry big map books in their car, and store their business contacts in a Rolodex. Today, we have email with digital signatures, navigation apps leveraging the GPS in our smartphones, and CRM web tools. Software can also automate other software, from identifying the best time for a meeting by reading the participants’ calendars and generating invitations with a link to start a video call to publishing pre-written content on a schedule. Verifying how software behaves is just another task ripe for automation. You can write code to check that the code you wrote behaves as expected. Code that checks other code – that’s what automated testing is. To understand what writing code that checks other code means, let’s turn to the programming interview all-time favorite: the “fizz-buzz” algorithm. Given an integer, print “fizz” if it’s divisible by three, “buzz” if it’s divisible by five, “fizz-buzz” if it’s divisible by three and five; otherwise, print the value itself. Chapter 1 Why test-Driven Development?
Page 20
4 Here’s one possible implementation: #!/usr/bin/env swift func fizzBuzz(_ number: Int) -> String { let divisibleBy3 = number % 3 == 0 let divisibleBy5 = number % 5 == 0 switch (divisibleBy3, divisibleBy5) { case (false, false): return "\(number)" case (true, false): return "fizz" case (false, true): return "buzz" case (true, true): return "fizz-buzz" } } To test this code, we can use a script that calls fizzBuzz(_:) with different numbers and prints “PASSED” if the value is correct and “FAILED” if it isn’t: func testFizzBuzz() { if fizzBuzz(3) == "fizz" { print("PASSED") } else { print("FAILED") } if fizzBuzz(5) == "buzz" { print("PASSED") } else { print("FAILED") } // and so on } Chapter 1 Why test-Driven Development?
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
Back to List