In my – admittedly limited – perception unit testing in C++ projects does not seem as widespread as in Java or the dynamic languages like Ruby or Python. Therefore I would like to show how easy it can be to integrate unit testing in a CMake-based project and a continuous integration (CI) server. I will briefly cover why we picked googletest, adding unit testing to the build process and publishing the results.
Why we chose googletest
There are a plethora of unit testing frameworks for C++ making it difficult to choose the right one for your needs. Here are our reasons for googletest:
- Easy publishing of result because of JUnit-compatible XML output. Many other frameworks need either a Jenkins-plugin or a XSLT-script to make that work.
- Moderate compiler requirements and cross-platform support. This rules out xUnit++ and to a certain degree boost.test because they need quite modern compilers.
- Easy to use and integrate. Since our projects use CMake as a build system googletest really shines here. CppUnit fails because of its verbose syntax and manual test registration.
- No external dependencies. It is recommended to put googletest into your source tree and build it together with your project. This kind of self-containment is really what we love. With many of the other frameworks it is not as easy, CxxTest even requiring a Perl interpreter.
Integrating googletest into CMake project
- Putting googletest into your source tree
- Adding googletest to your toplevel
CMakeLists.txtto build it as part of your project:add_subdirectory(gtest-1.7.0)
- Adding the directory with your (future) tests to your toplevel
CMakeLists.txt:add_subdirectory(test)
- Creating a CMakeLists.txt for the test executables:
include_directories(${gtest_SOURCE_DIR}/include) set(test_sources # files containing the actual tests ) add_executable(sample_tests ${test_sources}) target_link_libraries(sample_tests gtest_main) - Implementing the actual tests like so (@see examples):
#include "gtest/gtest.h" TEST(SampleTest, AssertionTrue) { ASSERT_EQ(1, 1); }
Integrating test execution and result publishing in Jenkins
- Additional build step with shell execution containing something like:
cd build_dir && test/sample_tests --gtest_output="xml:testresults.xml"
- Activate “Publish JUnit test results” post-build action.
Conclusion
The setup of a unit testing environment for a C++ project is easier than many developers think. Using CMake, googletest and Jenkins makes it very similar to unit testing in Java projects.