I wrote an article about six months ago on code coverage in C++, which is part of my article Agile C++ Development and Testing with Visual Studio and TFS. In that article, I showed how to use a command line to create code coverage because I was under the impression that Visual Studio 2010 didn’t support C++ code coverage. I had tried it, but couldn’t get it to work at the time.
It turns out there is a way to use capture code coverage directly in Visual Studio (or in on a TFS build server) without any customization. The trick, as it turns out, is that you have to turn on the /Profile switch in the linker.
Including ALL of your Code
If you’re using static libraries, as described in Writing Unit Tests in Visual Studio for Native C++, you will need to make a change to ensure all of your code is included. By default, the linker only includes code from static libraries that is actually used. So if you don’t have a unit test that hits some code, it won’t show up in the code coverage results. That means you won’t be able to find dead code. To fix this problem, you need to turn off linker optimizations:
The /OPT:NOREF switch will include all your code in the test DLL.
Turning on C++ Code Coverage
Right click on your DLL (the test DLL in my case since I use a static library to link the test library into the C++/CLI test project, see Writing Unit Tests in Visual Studio for Native C++) and turn on the /PROFILE linker switch:
Once you do this, you’ll be able to use the testsettings file to specify which DLLs to instrument. Double-click the testsettings file, click Data and Diagnostics, then click Code Coverage to check the box in the Enabled column:
Finally, click Configure, and then check the DLLs that you want to be instrumented, which in this case is the MyCodeTests.dll file that contains both the test code and the product code.
Excluding Test Classes from Code Coverage
If you’re using static libraries and C++/CLI for testing as I described in Writing Unit Tests in Visual Studio for Native C++, you may have noticed that your test methods also show up in the code coverage results. You can exclude all the methods in a test class from code coverage using the ExcludeFromCodeCoverageAttribute in front of the class. For example:
public ref class MyClassFixture
Now all the methods in your test class will be excluded from the code coverage results.
Note: You’ll need SP1 of Visual Studio 2010 in order to see lines colored to show coverage information.