This is the third and last installment of a series that teaches you how to mock and stub system classes in Swift. In this tutorial, we unit test the AddLocationViewViewModel class.
Remember from the previous installment of this series that our goal is to mock the Core Location framework and stub the responses of any geocoding requests we send to Apple’s location services. This is necessary if we want to create a fast and reliable test suite. Being in control of the test environment is key if your goal is creating a robust test suite.
Speed and reliability are key elements of a robust test suite. But for a test suite to be fast and reliable, you need to be in control of the environment in which the test suite is run. You don’t want to write a unit test that depends on the response of an API request. Right? For such a unit test to be fast and reliable, the API your application interacts with needs to be mocked and its response stubbed.
A few days ago, I wrote about unit testing private methods in Swift. I briefly touched on a topic that is very often overlooked by developers, especially those that are new to unit testing. What are you testing?
Unit testing a Swift project is quite different from unit testing a project written in Objective-C. For those that are used to the flexibility of the Objective-C runtime, it may feel as if your hands are tied behind your back.
Even though writing unit tests is not my favorite aspect of software development, over the years, I have come to enjoy and appreciate it. Not only is a robust test suite invaluable for any software project, it also makes you a better programmer.
Now that you know how to enable code coverage in Xcode, you may want to export the test results or generate a report you can share. Even though Xcode currently does not offer this option, nothing stops you from using the data Xcode generates.
One of the announcements that excited me most during last year’s WWDC was Xcode’s built-in support for code coverage. As of Xcode 7, you no longer have to jump through a bunch of hoops to find out how well your test suite has covered your code.