Mocking Network Calls in Swift

Yes, you can test your code without making genuine network calls

Steven Curtis
6 min readApr 29, 2020

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

--

--