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:
Architecting SwiftUI apps with MVC and MVVM: Although you can create an app simply by throwing some code together, without best practices and a robust architecture, you’ll soon end up with unmanageable spaghetti code. Learn how to create solid and maintainable apps with fewer bugs using this free guide.