Viewing Code Coverage

You might have an intuitive sense of what code needs the most automated testing, but as your projects grow, it’s possible you’ll overlook important parts of the code that should be tested. Helper methods, convenience initializers, extensions on existing types… there’s lots of code you can bang out quickly to get a feature done, and not really realize its implications for unit testing.

Xcode’s tool to help with this is a UI to show code coverage: how much of the codebase is exposed to automated testing.

Code coverage is not enabled by default. To use it, you need to edit the current scheme, select the Test action, go to the Options tab, and select the “Code Coverage” check box. By default, Code Coverage will be evaluated for all your targets; if you don’t want to collect or show it for certain targets, use the pop-up to select “some targets”, and then add the targets to the table with the plus (+) button, as seen in the following figure:

images/testing/xcode-scheme-selector-code-coverage.png

Once you run unit tests after enabling code coverage, a visual representation of the coverage is shown in the right gutter of the source code editor. The gutter has red regions denoting code sections that are not hit by tests, and green showing those that are covered. Uncovered areas are always shown, while covered areas only appear as you mouse over the right gutter.

There’s also a number that shows how many times each section of code is covered by the tests. This helps explain how the code coverage tool actually works under the hood. It’s not doing some fancy LLVM profiling to analyze the code and figure out what tests call what code; it simply counts up which lines of code get executed during the actual test runs:

images/testing/xcode-editor-area-code-coverage.png

This also illuminates one important side effect of how the code coverage tool works: since the app itself is brought up to a normal running state before any of the tests are run, all code in your normal startup path is indicated as having been tested. That means a completely empty iOS app project will still show the AppDelegate’s application(_:didFinishLaunchingWithOptions:) and the ViewController’s viewDidLoad as being covered by tests, simply because the test runner will have to run these methods as part of starting up the app, even though they’re not actually being tested yet.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.17