Unit testing C++

I use XCode to develop C++ command line applications and would like to use the unit testing framework to do code coverage analysis. However it is hard to find documentation on this topic. Is this possible to do?


On that same topic, can anyone point to detailed documentation or examples on Code coverage in Xcode?


Thanks - David

I have not tried unit testing C++ code with XCTest, but with Apple's old unit testing framework, OCUnit, you could unit test C++ code by adding a unit testing bundle target to your project. When creating test classes, use Objective-C, not Swift, and give the file the extension .mm so Xcode treats the file as Objective-C++. Your test classes must be Objective-C++ to test C++ code. If you get linker errors, you will have to make your C++ files members of the unit testing target.


Xcode's code coverage isn't too difficult to set up. Open the scheme editor, select the Test step, and select the Gather coverage data checkbox. If you need more detailed information, the following article may help you:


Xcode 7: Code Coverage

Many thanks for the reply. I need to be able to run the C++ on both Macs and Linux so realistically should work with .cpp or .C extensions to make the porting smooth. Also I tried a very simple example to play with code coverage in tests; this didn't seem to work but it may have been that the example was too simple to have much code to cover..


On reflection I think I will probably need to just use gcov directly and build C++ wrappers around the tests to work with this.


Thanks - David

You can keep the .cpp extension and just indicate the file type as Objective-C++ source. Then of course you'll need some macros to make the test classes appear like Objective C on the Mac and C++ on Linux. We're currently doing this for Mac/Windows cross platform tests

@Harpo_Dave The recipe from szymczyk was spot on.


" I need to be able to run the C++ on both Macs and Linux so realistically should work with .cpp or .C extensions to make the porting smooth"


You only need to use the .mm extensions for the Test code, which is Objective-C++. Basically, you write tests in Objective-C and they can invoke any C++ code you like. You then get the test-runner benefits of XCode.


The Objective-C++ test files include your C++ headers exactly as you would writing separate C++ unit tests in any other framework.


If you want portable unit tests you can also run on Linux, try Google Test aka gtest. It is directly supported by Jetbrains' AppCode IDE which I highly recommend to anyone working in C++ on OS X. XCode is somewhat crippled for C++ and even for Objective-C++ (no refactoring support, for example).

Unit testing C++
 
 
Q