CTest Basics
CTest is CMake's test driver. It doesn't care which test framework you use (GoogleTest, Catch2, doctest, a plain main() that returns non-zero on failure, a Python script): a test is simply a command with an expected outcome. You register tests in CMakeLists.txt, and ctest runs them, in parallel if you like, with filtering, timeouts and reports.
enable_testing() # or include(CTest), which also adds the CDash options
add_test(NAME <name> COMMAND <program> [args...] [WORKING_DIRECTORY dir])enable_testing() must be called in the top-level CMakeLists.txt (it makes CMake write the CTestTestfile.cmake files ctest reads). add_test can then be used in any directory. When COMMAND names an executable target, CMake substitutes the built file's path.
A first test suite
No framework needed: a test program reports failure through its exit code.
mkdir -p mathx/tests && cd mathx
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(MathX LANGUAGES CXX)
add_library(mathx mathx.cpp)
target_include_directories(mathx PUBLIC .)
enable_testing()
add_subdirectory(tests)
CM
cat > mathx.hpp <<'SRC'
#pragma once
int gcd(int a, int b);
int lcm(int a, int b);
SRC
cat > mathx.cpp <<'SRC'
#include "mathx.hpp"
int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }
int lcm(int a, int b) { return a / gcd(a, b) * b; }
SRC
cat > tests/CMakeLists.txt <<'CM'
add_executable(test_gcd test_gcd.cpp)
target_link_libraries(test_gcd PRIVATE mathx)
add_test(NAME gcd.basic COMMAND test_gcd basic)
add_test(NAME gcd.zero COMMAND test_gcd zero)
add_test(NAME lcm.basic COMMAND test_gcd lcm)
CM
cat > tests/test_gcd.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include "mathx.hpp"
#define CHECK(expr) do { if (!(expr)) { std::printf("FAILED: %s (line %d)\n", #expr, __LINE__); return 1; } } while (0)
int main(int argc, char** argv) {
const char* which = argc > 1 ? argv[1] : "";
if (!std::strcmp(which, "basic")) { CHECK(gcd(12, 18) == 6); CHECK(gcd(7, 5) == 1); }
else if (!std::strcmp(which, "zero")) { CHECK(gcd(0, 9) == 9); CHECK(gcd(9, 0) == 9); }
else if (!std::strcmp(which, "lcm")) { CHECK(lcm(4, 6) == 12); CHECK(lcm(0, 5) == 0); }
else return 2;
std::printf("%s: all checks passed\n", which);
return 0;
}
SRC
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build > /dev/null
ctest --test-dir buildTest project /home/learner/mathx/build
Start 1: gcd.basic
1/3 Test #1: gcd.basic ........................ Passed 0.00 sec
Start 2: gcd.zero
2/3 Test #2: gcd.zero ......................... Passed 0.00 sec
Start 3: lcm.basic
3/3 Test #3: lcm.basic ........................ Passed 0.00 sec
100% tests passed out of 3
Total Test time (real) = 0.01 sec
All three passed. One test program serves three tests here: each add_test runs it with a different argument, so CTest reports, times and filters them separately (ctest -R gcd runs only the first two). The numbers 1/3, 2/3 are the progress; Test #1 is the test's index, which stays the same when you filter.
When a test fails
mkdir -p failing && cd failing
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Failing LANGUAGES CXX)
enable_testing()
add_executable(check check.cpp)
add_test(NAME parses_numbers COMMAND check 42)
add_test(NAME rejects_words COMMAND check abc)
CM
cat > check.cpp <<'SRC'
#include <cstdio>
#include <cstdlib>
int main(int argc, char** argv) {
char* end;
long v = std::strtol(argv[1], &end, 10);
std::printf("input '%s' -> %ld\n", argv[1], v);
if (*end != '\0') { std::printf("error: '%s' is not a number\n", argv[1]); return 1; }
return 0;
}
SRC
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build > /dev/null
unset CTEST_OUTPUT_ON_FAILURE # the course image sets it; show the default first
cd build
ctest
echo "exit code: $?"
echo "=== again, with the failing test's output"
ctest --output-on-failure -R rejectsTest project /home/learner/failing/build
Start 1: parses_numbers
1/2 Test #1: parses_numbers ................... Passed 0.00 sec
Start 2: rejects_words
2/2 Test #2: rejects_words ....................***Failed 0.00 sec
50% tests passed, 1 tests failed out of 2
Total Test time (real) = 0.00 sec
The following tests FAILED:
2 - rejects_words (Failed)
Errors while running CTest
Output from these tests are in: /home/learner/failing/build/Testing/Temporary/LastTest.log
Use "--rerun-failed --output-on-failure" to re-run the failed cases verbosely.
exit code: 8
=== again, with the failing test's output
Test project /home/learner/failing/build
Start 2: rejects_words
1/1 Test #2: rejects_words ....................***Failed 0.00 sec
input 'abc' -> 0
error: 'abc' is not a number
0% tests passed, 1 tests failed out of 1
Total Test time (real) = 0.00 sec
The following tests FAILED:
2 - rejects_words (Failed)
Errors while running CTest
ctestexits non-zero when any test fails (8 here), so CI marks the job as failed.- By default it hides test output.
--output-on-failureprints the output of failing tests, which is what you want in CI (the environment variableCTEST_OUTPUT_ON_FAILURE=1makes it the default; the course image sets it). Testing/Temporary/LastTest.login the build directory has the full output of every test from the last run.
rejects_words "failed" because the program correctly rejected abc with exit code 1. That test is supposed to fail, which the next lesson expresses with the WILL_FAIL property.
Running ctest
ctest --test-dir build # from anywhere (CMake 3.20+); or cd build && ctest
ctest --test-dir build -j 8 # parallel (CTEST_PARALLEL_LEVEL sets the default)
ctest --test-dir build -R gcd # only tests whose name matches a regex
ctest --test-dir build -E slow # exclude by regex
ctest --test-dir build -N # list tests without running them
ctest --test-dir build --rerun-failed # only the tests that failed last time
ctest --test-dir build -C Release # multi-config generators: which configuration's binaries
ctest --test-dir build -V # verbose: show every command line and all outputUsing a test framework
Frameworks plug into CTest in two ways: register the whole test binary as one test (add_test(NAME unit COMMAND unit_tests)), or let a module discover every test case and register each one separately, so ctest -R can pick individual cases:
include(GoogleTest)
gtest_discover_tests(unit_tests) # GoogleTest: runs the binary with --gtest_list_tests at build time
include(Catch) # shipped with Catch2
catch_discover_tests(unit_tests)Getting GoogleTest or Catch2 into the build is a dependency question: FetchContent, or a package manager as in C/C++ Packages, whose Mini Project uses Catch2 with CTest.
Test yourself
What decides whether a plain add_test command passes?
- Its output
- Its exit code: 0 passes, anything else fails (unless test properties say otherwise)
- Whether it prints PASSED
- The framework used
Where must enable_testing() be called?
- In every directory with tests
- In the top-level CMakeLists.txt (before or around the add_subdirectory calls)
- In the test executable
- Only in CI
Which option prints the output of failing tests?
-V--output-on-failure-N--rerun-failed