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:
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.
Create a separate directory for your tests and create test source files there. For example, you can create a file named test_example.cpp
.
Use the framework's syntax to write your tests. Here's a simple example using Google Test:
#include
TEST(SampleTest, AssertionTrue) {
EXPECT_TRUE(true);
}
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)
Finally, build your project using CMake and run your tests using the following commands:
mkdir build
cd build
cmake ..
make
ctest
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?