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:
- In the test, we will use a mock object of a
URLSession
class instead of the realURLSession
instance. To be able to replace the realURLSession
instance with the mock, we need a protocol that defines the interface we want to replace. - Add the following protocol definition...