If you're working on a cross-platform C++ library, eventually you'll want to write tests that also run on all of your supported platforms. Google Test is a popular C++ unit testing library that has been used in major projects including LLVM and OpenCV. While the project may seem out-of-date (listing OS X 10.4 in the requirements), it's still actively maintained. What's more, we can set up Google Test such that it plays nicely with Xcode's unit testing tools and UI.
To get started, we'll add the Google Test GitHub repository as a submodule of our C++ project. While there are tagged releases of Google Test on GitHub, they haven't been updated in almost three years and the master branch includes useful fixes and compatibility improvements. From the project's root directory, run:
git submodule add firstname.lastname@example.org:google/googletest.git
Since tests written with the Google Test framework are typically executed with a separate command line tool, we create a new Command Line Tool target in Xcode and call it something along the lines of
<MyProject>Tests. Now we need to link this target with the Google Test framework. Conveniently, Google includes an Xcode project file we can reference by dragging into our Files navigator. The project file can be found under
Once the project has been added, select it in Xcode's File navigator and switch to the Build Settings tab. If your project uses LLVM's
libc++ instead of the GNU C++ standard library, you'll have to also build Google Test with "C++ Standard Library" set to
libc++ support, otherwise you'll get linker errors due to ABI mismatches. You'll also need to target OS X 10.7 or better.
Next, we need to switch back to our C++ library's Xcode project and select the Tests target we added. Then select the Build Phases tab, and add the Google Test static library as a target dependency. Once that's done, we need to also add the static library in the "Linking Binary with Libraries" list. Finally, switch to "Build Settings" and add "$SRCROOT/googletest/googletest/include". You can now add tests to the tests target's
main.cpp file. Any tests you write should be portable across all the platforms you library runs on. You might have to change "" to <>. Makefile. LInk to GOogle sample. If you run the target, you'll see output from the tests in the console. As a best practice, it's a good idea to put tests in separate source (*.cpp) file instead of packing them all into
main.cpp. This will also be important in the next few steps.
While we now have tests that can be run on different platforms, we