Articles, podcasts and news about Swift development, by John Sundell.

Gathering test coverage in Xcode

Published on 18 Sep 2019
Discover 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:

How to enable code coverage

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:

How to access code coverage reports

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:

How to display code coverage inline

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!