Posted Joe Chu misc4 minutes read (About 568 words)0 visits
Add GTest to C++ Projects
Add GoogleTest framework to any C++ projects using CMake.
1. Introduction
This tutorial demonstrates the seamless integration of the GoogleTest framework into your pre-existing C++ project to facilitate unit testing. Its user-friendly nature simplifies the process and allows for straightforward inclusion within your CMakeLists.txt for easy compilation.
2. Project Structure
For demonstration purpose, we created a simple project.
# Add test files set(TEST_SOURCES tests/main.cpp tests/test.cpp )
# Add an executable for tests add_executable(runTests ${TEST_SOURCES}) target_link_libraries(runTests gtest gtest_main)
3. Test
1 2
# Run all test cases ./runTests
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
[==========] Running 4 tests from 1 test suite. [----------] Global test environment set-up. [----------] 4 tests from MathTest [ RUN ] MathTest.Add [ OK ] MathTest.Add (0 ms) [ RUN ] MathTest.Subtract [ OK ] MathTest.Subtract (0 ms) [ RUN ] MathTest.Multiply [ OK ] MathTest.Multiply (0 ms) [ RUN ] MathTest.Divide [ OK ] MathTest.Divide (0 ms) [----------] 4 tests from MathTest (0 ms total)
[----------] Global test environment tear-down [==========] 4 tests from 1 test suite ran. (0 ms total) [ PASSED ] 4 tests.
1 2
# Run single test ./runTests --gtest_filter=MathTest.Add
1 2 3 4 5 6 7 8 9 10 11
Note: Google Test filter = MathTest.Add [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from MathTest [ RUN ] MathTest.Add [ OK ] MathTest.Add (0 ms) [----------] 1 test from MathTest (0 ms total)
[----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test.