Unit testing in C++ with doctest and CTest
How to write and run C++ unit tests: test cases, CHECK vs REQUIRE, floating-point comparisons, testing exceptions, and running groups of tests with CTest labels.
A unit test is a small program that calls your code with known input and checks the result. Tests turn "I think it works" into "it works, and here's proof", and they tell you immediately when a later change breaks something.
The examples use doctest, a single-header framework, and CTest, which comes with CMake (see setting up C++ with CMake).
A first test
#include "doctest.h"
#include "roman/numerals.hpp"
TEST_CASE("subtractive pairs") {
CHECK(roman::to_roman(4) == std::string("IV"));
CHECK(roman::to_roman(9) == std::string("IX"));
CHECK(roman::to_roman(1994) == std::string("MCMXCIV"));
}One .cpp file in the test executable defines DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN before including
doctest.h; that provides main().
CHECK or REQUIRE
TEST_CASE("parses a reading") {
const auto reading = frost::parse_reading("freezer-2,-18.5");
REQUIRE(reading.has_value()); // stop here if it's empty...
CHECK(reading->sensor == "freezer-2"); // ...because these would crash
}Use REQUIRE for preconditions of the rest of the test, CHECK for everything else.
Comparing floating-point numbers
Floating-point arithmetic isn't exact, so never compare with ==:
CHECK(summary.average == doctest::Approx(5.0 / 3.0));(And for money, don't use floating point at all; see the invoice totals project.)
Testing errors
CHECK_THROWS_AS(invoice_totals({{0, 100, 19}}), std::invalid_argument);
CHECK_FALSE(parse_time("24:00").has_value());Loops of cases and CAPTURE
When many inputs should behave the same way, loop over them and CAPTURE the current one so a
failure tells you which:
for (const char* line : {"", "ERR", "freezer-2,", "freezer-2,5abc"}) {
CAPTURE(line);
CHECK_FALSE(frost::parse_reading(line).has_value());
}Running groups of tests with CTest
Register one test executable per area, with a label:
add_test(NAME tests_m1 COMMAND tests_m1)
set_tests_properties(tests_m1 PROPERTIES LABELS m1)ctest --test-dir build -L m1 --output-on-failure # only label m1, show output of failuresThat's exactly how Devventura milestones work: each milestone's tests carry its label.
What to test
- Every acceptance criterion from the ticket (see working with tickets).
- Both sides of every boundary: 15 and 16 minutes, 89 and 90 points.
- Invalid input, empty input, very large input.
- That a refused operation changes nothing.
Questions and answers
- Which C++ test framework should I use?
- doctest, Catch2 and GoogleTest are all good. doctest is a single header and compiles fast, which makes it easy to drop into small projects; GoogleTest is common in large companies. The ideas are the same.
- What's the difference between CHECK and REQUIRE?
- A failing CHECK records the failure and continues the test case. A failing REQUIRE stops the test case, which you want when the rest of the test can't run, for example before dereferencing an optional.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Chronicle Clocks
Roman numerals for Chronicle Clocks
Convert years and numbers to Roman numerals for Chronicle's engraving machines, and check the numerals customers type in.
- lookup tables
- greedy algorithms
- string building
- validation
Ledgerly
Invoice totals for Ledgerly
Read amounts, compute net, VAT and gross totals to the cent, and never lose a cent to floating point.
- integer arithmetic
- rounding
- parsing
- exceptions
Market Square
Weekly sales report for Market Square
Parse Market Square's sales export, quotes and all, and turn it into revenue per category without letting one bad row spoil the report.
- state machines
- CSV quoting
- error reporting
- aggregation
Read next
- How to work with tickets and acceptance criteria as a junior developer
How to read a ticket, find what it doesn't say, ask good questions, and turn acceptance criteria into tests, with examples from realistic product tickets.
- Code review checklist for junior developers
What senior engineers look for in a code review, as a practical checklist: correctness, edge cases, tests, naming, structure and performance, with C++-specific points.