Book Image

Test-Driven iOS Development with Swift - Fourth Edition

By : Dr. Dominik Hauser
5 (1)
Book Image

Test-Driven iOS Development with Swift - Fourth Edition

5 (1)
By: Dr. Dominik Hauser

Overview of this book

Test-driven development (TDD) is a proven way to find software bugs earlier on in software development. Writing tests before you code improves the structure and maintainability of your apps, and so using TDD in combination with Swift 5.5's improved syntax leaves you with no excuse for writing bad code. Developers working with iOS will be able to put their knowledge to work with this practical guide to TDD in iOS. This book will help you grasp the fundamentals and show you how to run TDD with Xcode. You'll learn how to test network code, navigate between different parts of the app, run asynchronous tests, and much more. Using practical, real-world examples, you'll begin with an overview of the TDD workflow and get to grips with unit testing concepts and code cycles. You'll then develop an entire iOS app using TDD while exploring different strategies for writing tests for models, view controllers, and networking code. Additionally, you'll explore how to test the user interface and business logic of iOS apps and even write tests for the network layer of the sample app. By the end of this TDD book, you'll be able to implement TDD methodologies comfortably in your day-to-day development for building scalable and robust applications.
Table of Contents (17 chapters)
Section 1 –The Basics of Test-Driven iOS Development
Section 2 –The Data Model
Section 3 –Views and View Controllers
Section 4 –Networking and Navigation

Testing async/await code that communicates with URLSession

In 2021, Apple introduced async/await in Swift. With async/await, asynchronous code (for example, fetching information from a server) is easier to write and easier to understand. In this section, we will learn how to implement fetching data from a web server using the async/await APIs of the URLSession class; and we will do this, of course, using test-driven development.

Unit tests need to be fast and repeatable. This means we don't want to rely on a connection to a real server in our unit tests. Instead, we will replace the communication with the server with a mock object.

Follow these steps to implement fetching to-do items from a server:

  1. In the test, we will use a mock object of a URLSession class instead of the real URLSession instance. To be able to replace the real URLSession instance with the mock, we need a protocol that defines the interface we want to replace.
  2. Add the following protocol definition...