GoogleTest is widely used for C++ unit testing and CMake is a popular build system for C++ projects.
In this blog post, I will quickly demonstrate how to add GoogleTest unit tests to a C++ project using CMake and run the tests using CTest.
GoogleTest Using CMake
In this example, we created a simple C++ math library project and added GoogleTest unit tests using CMake. The example could be found at GoogleTest-CMake-Examples on GitHub.
Project Layout
Normally, a C++ project layout could be organized as follows.
$ ctest --test-dir build/ --verbose Internal ctest changing into directory: /mnt/build UpdateCTestConfiguration from :/mnt/build/DartConfiguration.tcl UpdateCTestConfiguration from :/mnt/build/DartConfiguration.tcl Test project /mnt/build Constructing a list of tests Done constructing a list of tests Updating test list for fixtures Added 0 tests to meet fixture requirements Checking test dependency graph... Checking test dependency graph end test 1 Start 1: AllAddTests
1: Test command: /mnt/build/examples/math/tests/add_test/add_test 1: Working Directory: /mnt/build/examples/math/tests/add_test 1: Test timeout computed to be: 10000000 1: Running main() from /tmp/googletest-1.15.2/googletest/src/gtest_main.cc 1: [==========] Running 2 tests from 2 test suites. 1: [----------] Global test environment set-up. 1: [----------] 1 test from AddTest1 1: [ RUN ] AddTest1.BasicAssertions 1: [ OK ] AddTest1.BasicAssertions (0 ms) 1: [----------] 1 test from AddTest1 (0 ms total) 1: 1: [----------] 1 test from AddTest2 1: [ RUN ] AddTest2.BasicAssertions 1: [ OK ] AddTest2.BasicAssertions (0 ms) 1: [----------] 1 test from AddTest2 (0 ms total) 1: 1: [----------] Global test environment tear-down 1: [==========] 2 tests from 2 test suites ran. (0 ms total) 1: [ PASSED ] 2 tests. 1/2 Test #1: AllAddTests ...................... Passed 0.02 sec test 2 Start 2: AllSubtractTests
2: Test command: /mnt/build/examples/math/tests/subtract_test/subtract_test 2: Working Directory: /mnt/build/examples/math/tests/subtract_test 2: Test timeout computed to be: 10000000 2: Running main() from /tmp/googletest-1.15.2/googletest/src/gtest_main.cc 2: [==========] Running 2 tests from 2 test suites. 2: [----------] Global test environment set-up. 2: [----------] 1 test from SubtractTest1 2: [ RUN ] SubtractTest1.BasicAssertions 2: [ OK ] SubtractTest1.BasicAssertions (0 ms) 2: [----------] 1 test from SubtractTest1 (0 ms total) 2: 2: [----------] 1 test from SubtractTest2 2: [ RUN ] SubtractTest2.BasicAssertions 2: [ OK ] SubtractTest2.BasicAssertions (0 ms) 2: [----------] 1 test from SubtractTest2 (0 ms total) 2: 2: [----------] Global test environment tear-down 2: [==========] 2 tests from 2 test suites ran. (0 ms total) 2: [ PASSED ] 2 tests. 2/2 Test #2: AllSubtractTests ................. Passed 0.00 sec