While QtCreator is an excellent IDE for Qt projects it has no built-in support for unit testing and test coverage. In that article I’ll show you how to unit test your Qt application, automatically generate LCOV html coverage report and view them in a browser with just one click.
First of all I assume you have the gcov library as well as lcov and genhtml applications installed on your system. Next you need to tell QtCreator how to compile and link against that library. You do that by adding the following lines to the pro file of your unit test project:
The second step is to download my processCoverage.sh bash script from github. Essentially it analyzes recursively a path for coverage data provided by the gcov library. That data is created when programs linked against the gcov library are run. The script processes that coverage data using lcov and creates the html report using genhtml.
Putting The Pieces Together
The goal is to just click the QtCreator’s Run button to start the unit test, generate the coverage report and have it shown in a browser. To do that you need to add a custom run configuration to the unit test project. The following screenshot illustrates the steps:
- Select the Project button on the left sidebar.
- Click to the Run tab to switch to the Run Settings.
- From the Add drop down menu select Custom Executable and make sure the executable and working directory are correct. Also you should check Run in terminal to see the output of failed tests and coverage processor.
In the Arguments field you tell QTestLib (Qt 4.8 | Qt 5.0) to produce xml output which will give you in the terminal just the line of how many tests failed as an indicator for why coverage data might not be available or incomplete. Also the processCoverage.sh script is called with a file pattern and finally the index.html of the coverage report is sent to a browser which is Opera in that example.
Here’s a template of the argument line. You need to insert the paths to the gnco files created by gcov, to the processCoverage.sh script, to the location where you want the lcov report generated to, your project name, and your browser:
An example in full length:
With A Single Click You Get
Now, when you click the Run button in QtCreator a terminal appears printing in the second line the number of failed tests followed by lcov logs.
Once LCOV is finished the coverage report will be opened in your web browser.
Thanks for reading. Feedback is welcome.
ZIP of a simple Qt 4.8.4 example project: LCOVblog.tar.gz
Changed links of gists linking to the new improved argument line for complex project structures.