Member-only story
Mocking Network Calls in Swift
Yes, you can test your code without making genuine network calls

When testing there are various reasons why you might not want to test against the real version of an API. This might be because you want to make sure that you are only testing one class or method of your code at once (so you can separate out different pieces of your testing regime), or (as in this case) you don’t want to make real network calls (because they might be flaky or you might not guarantee that the network connection is available in your testing environment.
Difficulty: Beginner | Easy | Normal | Challenging
Prerequisites:
- Understand the difference between the terms subbing, mocking and faking (Guide HERE)
- We will be using Swift’s result type (guide HERE) within this post
- Be able to allow Arbitrary loads in your Plist settings (guide HERE)
Terminology
API: Application programming interface. A set of accessible tools for building software applications
Class: An object that defines properties and methods in common
Data Task: A task that retrieves the contents of a URL
Method: A function that defines the behaviour of object
Mocking: A fake response to the method call for of an object, allowing the checking of a particular method call or property
Result Type: A value that represents either a success or a failure, including an associated value in each case
The use of mocking
To be able to test network calls without actually hitting the remote server through thoseAPI
calls is an invaluable skill to learn.
Look, putting load on a server just to test might seem like a silly thing to do because of the straight cost of doing so but it’s more than that. Waiting for a response from a remote API
is slowwwwww and you are dependent on that API for your tests passing.