Gathering test coverage in XcodeDiscover page available: Unit Testing
Measuring the degree to which a project’s suite of unit tests covers its code base can be a great way to identify code paths that aren’t yet tested. While coverage data doesn’t tell us anything about the quality of our tests, it can still be an incredibly useful tool — especially when retrofitting a code base with tests, or when we’re unsure whether a certain condition or state is actually being tested.
However, Xcode won’t gather test coverage by default, but thankfully it’s really easy to enable. Start by pressing
⌥⌘U to bring up the current target’s test settings. Then open the Options tab, and check the Code Coverage checkbox, like this:
That’s it! Next, let’s actually make use of the coverage data that from now on will be generated each time we run our tests. One way to do that is to open up the Report Navigator (
⌘9), which will now show a coverage report for each subsequent testing session:
Finally, we can also enable our new coverage data to be shown inline as we’re coding. While some developers might find that distracting, it can be a great way to quickly spot code paths that need testing. To turn that on, use the Adjust Editor Options button located in the top-right corner of each editor:
As you can see above, any code paths that aren’t yet tested will now be highlighted using a red bar, and the iteration count will also be shown for all other paths. Really nice!
Support Swift by Sundell by checking out this sponsor:
Essential Developer: If you’re a mid/senior iOS developer who’s looking to improve both your skills and your salary level, then join this 100% free online crash course, starting on August 2nd. Learn how to apply truly scalable iOS app architecture patterns through a series of lectures and practical coding sessions.