Bubble Foundry


Generating iOS Code Coverage Reports

by Peter.

2013-11-13: I have found a better way to generate the coverage reports for all source files.

As part of the testing an iOS app, I want to make sure that I am actually covering important areas of my application with tests. Xcode 5 (and previous versions) has code coverage support, but it’s not obvious. Here’s what I did to get it working:

First, you need to enable code coverage for your app target (e.g. MyApp) under the project’s build settings by setting Generate Test Coverage Files and Instrument Program Flow to Yes. For both, setting to Yes for Debug and not Release should be sufficient. You’ll also need to enable Instrument Program Flow for the your test target (e.g. MyAppTests).

Then, because the iOS Simulator does not exit apps as normal when running app tests, you’ll need tell the tests to flush the coverage data upon finishing test execution. You do this by calling the __gcov_flush() C function, for instance in a test suite’s tearDown method:

#import <XCTest/XCTest.h>
#import <objc/runtime.h>
 
extern void __gcov_flush();
...
 
@implementation ObjectATests
 
+ (void)tearDown {
  __gcov_flush();
  [super tearDown];
}
 
....
@end

You can then run your tests as normal. Behind the scenes, .gcno (GNU Compiler Notes file) and .gcda (code coverage) files should have been created in the project’s Derived Data directory. You can find the directory by going to the Organizer in Xcode, selecting your project, and then clicking on the small arrow next to the Derived Data directory path. Once there, you’ll need to drill down into the directories to find the files. find . -name "*.gcda" -print is your friend. For example, you would find the files in something like ~/Library/Developer/Xcode/DerivedData/MyApp-/Build/Intermediates/MyApp.build/Debug-iphonesimulator/MyAppTests.build/Objects-normal/i386/.

Now that you have your code coverage files, you’ll want to view them. CoverStory and Xcoverage are free graphical apps which will display the original source code with annotated coverage information, while gcov and lcov can be used to create HTML reports, for instance as part of a continuous integration process.

NOTE: If coverage files are missing for some of the files being tested, make sure the .m files in question have been added to the test target as well as the main one.