Code Coverage Reports in iOS Projects
Introduction:
Code coverage is an important measure in the test phase of the life cycle of software development, which if our project has high test coverage suggests it has a low chance of containing undetected software bugs.
Requirements:
To understand this tutorial we need knowledge about:
- Fastlane
- Unit test in ios projects
- Continuous integration (CI)
The Problem:
In iOS projects, although XCode gives us code coverage measure, it isn’t practical to generate reports in continuous integration (CI), because we need some command line to use with a continuous integration service such as Jenkins, Travis or something similar.
The Solution:
To use command line, there are some options:
- xccov is a command line tool to view XCode Code Coverage Reports in human readable format.
- Slather is a framework that lets you generate test coverage reports for XCode projects & hook it into CI.
This tutorial we are choosing Slather, because it is easier to generate reports in cobertura or sonarqube formats and these formats are read by Azure DevOps and other CI platforms. Also, Slather is easily used by fastlane.
First, we need to install Slather, for that:
use the following command:
gem install slather
Or add to Gemfile and then execute bundle:
gem 'slather'
bundle
Note: To use Slather we should run our unit tests and gather the code coverage. For that, we will use the scan in fastlane with the following lane:
scan(
scheme: "CodeCoverageExample",
code_coverage: true,
clean: true,
derived_data_path: "../testOutput/",
skip_build: true
)
Finally, we can generate the code coverage report with slather and fastlane:
slather(
build_directory: "../testOutput/",
scheme: "CodeCoverageExample",
proj: "CodeCoverageExample.xcodeproj",
output_directory: "../testOutput/slatherOutput",
cobertura_xml: true,
ignore: ["Pods/*", "ThirdParty/*", “Frameworks/*"]
)
And the output is a cobertura.xml file which we can convert to html and it will look like the following image:
Full source code:
For a review of the full source code, please checkout my git repository of this tutorial. GitHub.