Catch2 is a popular C++ testing framework, and integrating it with CMake and CTest simplifies the testing workflow. This tutorial walks through the setup using Catch2 v3.
Prerequisites
- CMake 3.15+ installed
- A C++17-compatible compiler
- Git (to fetch Catch2)
Step 1: Add Catch2 via FetchContent
In your CMakeLists.txt, use FetchContent to download Catch2:
include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.5.0
)
FetchContent_MakeAvailable(Catch2)
This automatically downloads and builds the library.
Step 2: Link Catch2 to Your Tests
Create an executable for your tests and link Catch2:
add_executable(test_runner test.cpp)
target_link_libraries(test_runner Catch2::Catch2WithMain)
Catch2WithMain provides a default main function; you can also write your own with Catch2::Catch2.
Step 3: Register with CTest
Enable testing and add your test executable:
enable_testing()
add_test(NAME my_test COMMAND test_runner)
Now you can run ctest from the build directory.
Alternative: Subdirectory Method
If you prefer to keep Catch2 in your project, copy the catch2 folder into your source tree and add it with add_subdirectory:
add_subdirectory(lib/Catch2)
target_link_libraries(test_runner Catch2::Catch2WithMain)
This method avoids external fetching.
Writing Tests
Here's a simple example in test.cpp:
#include <catch2/catch_test_macros.hpp>
TEST_CASE("Addition works", "[math]") {
REQUIRE(1 + 1 == 2);
}
Build with cmake --build . and run with ctest or directly ./test_runner.
Catch2 v3 integrates smoothly with CMake's modern packaging, making it easy to add robust unit testing to any C++ project.