How do I write unit tests and add test targets in CMake for C++?

Writing unit tests in C++ involves using a testing framework such as Google Test. To integrate unit tests with CMake, you can follow these steps:

  1. Set Up Your Testing Framework

    Start by including the testing framework in your project. For Google Test, you may want to clone the repository or use a package manager to include it in your project.

  2. Create Your Test Files

    Create a separate directory for your tests and create test source files there. For example, you can create a file named test_example.cpp.

  3. Writing Your Tests

    Use the framework's syntax to write your tests. Here's a simple example using Google Test:

    #include 
    
    TEST(SampleTest, AssertionTrue) {
        EXPECT_TRUE(true);
    }
                
  4. Add to Your CMakeLists.txt

    Add test targets in your CMakeLists.txt file to ensure that unit tests are compiled and can be run. Here’s an example:

    cmake_minimum_required(VERSION 3.10)
    
    # Project setup
    project(MyProject)
    
    # GoogleTest setup
    enable_testing()
    find_package(GTest REQUIRED)
    include_directories(${GTEST_INCLUDE_DIRS})
    
    # Add your main application
    add_executable(MyApp src/main.cpp)
    
    # Add your tests
    add_executable(MyTests test/test_example.cpp)
    target_link_libraries(MyTests GTest::GTest GTest::Main)
    
    # Register your tests
    add_test(NAME MyUnitTest COMMAND MyTests)
                
  5. Build and Run Your Tests

    Finally, build your project using CMake and run your tests using the following commands:

    mkdir build
    cd build
    cmake ..
    make
    ctest
                

C++ unit tests Google Test CMake testing framework write tests integrate tests