Let's take a look at a method of mocking out classes in our project, which will make writing tests much easier. The basic premise we’re going to use was covered by Joe Masilotti on his blog.
Swift (at the time of this writing) does not have any official mocking support. So, in the meantime, we’re going to take advantage of extensions to get the job done. The basic idea is: we write a protocol containing all the methods and properties we want to use from an external API, then we extend that API to implement the protocol. Let’s see what that looks like for
Since the methods and properties match exactly, the extension can be empty. This is the ideal case, since it allows us to mock out our dependencies at the lowest level without having to write any code that won’t be tested. That won’t always be the case, however.
What if a class you want to mock happens to have a property whose type also needs mocking? For instance, if we wanted the
Since we’re adding a new property, the
What happens when we need the
That looks like a lot of code, so let’s step through it:
1. Here we’ve added a delegate property to our
2. Here is where we define our delegate protocol. The methods have the same signature as the
3. This is where we create a “proxy” class. It’s main purpose is to act as the
4. Here we make sure to set the underlying location manager’s delegate to our proxy class.
5. Here we listen to any relevant delegate methods, and call the corresponding method on our custom delegate. Since the methods are so similar, we simply need to switch the location manager parameter out and use our proxy instead.
Once this layer is in place, it’s trivial to mock out the dependency for tests like so:
You’d create an instance of the above class in your test, and easily be able to verify how your other code uses it. Things can get a bit out of hand, depending on what API you’re trying to mock. But it’s important to solidify this base layer, since it allows you to test all of the interesting code that will make up your app in an easy and quick way. If I’ve made any mistakes, or if you have any questions, please leave a comment below. Thanks for reading!