Handling errors
To test the handling of errors in the URLSession call to the web service, we first need to enhance URLSessionProtocolMock. Follow these steps to test that an error in fetching data is passed down to the caller of the APIClient instance:
- Add the following property to
URLSessionProtocolMock:// URLSessionProtocolMock.swift var dataForDelegateError: Error?
- Next, add the following handling of the error to the start of
data(for:delegate:):// URLSessionProtocolMock.swift if let error = dataForDelegateError { throw error }
If there is an error set to the dataForDelegateError property, we throw it before we do anything else in this method.
- Now, we are ready to add the test method to
APIClientTests:// APIClientTests.swift func test_toDoItems_whenError_shouldPassError() async throws { let urlSessionMock = URLSessionProtocolMock() let expected = NSError(domain: "", code: 1234) urlSessionMock.dataForDelegateError...