Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. A test without a framework
    4. Catch2: TEST_CASE, REQUIRE and CHECK
    5. Shared setup and errors: SECTION and REQUIRE_THROWS_AS
    6. A library, an app and tests
    7. What to test
    8. Which one should I use?
    9. Under the hood
    10. Common pitfalls
    11. Linking Catch2 without its main
    12. A test that can’t fail
    13. Try it yourself

    Module 8 · Organizing a project

    8.4Testing

    Write automated tests that check your code every time you build: a plain test program first, then Catch2 with TEST_CASE, REQUIRE, CHECK and SECTION, floating-point comparisons, and a CMake project with a library, an app and tests run by CTest.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. A test without a framework
    4. Catch2: TEST_CASE, REQUIRE and CHECK
    5. Shared setup and errors: SECTION and REQUIRE_THROWS_AS
    6. A library, an app and tests
    7. What to test
    8. Which one should I use?
    9. Under the hood
    10. Common pitfalls
    11. Linking Catch2 without its main
    12. A test that can’t fail
    13. Try it yourself

    Key terms

    automated test
    Code that calls your code with known inputs and checks the results, so a program, not a person, decides whether it still works.
    test framework
    A library that runs your tests and reports which ones failed, where, and with what values. This lesson uses Catch2.
    test case (TEST_CASE)
    One named test: a block of code with checks in it. A test program usually has many.
    assertion (REQUIRE, CHECK)
    One check inside a test case. REQUIRE stops the test case when it fails; CHECK records the failure and goes on.
    SECTION
    A part of a Catch2 test case. The test case runs once for each section, from the top, so every section starts from the same setup.
    matcher
    An object that describes what a value should be, like WithinRel(0.3). Used with REQUIRE_THAT and CHECK_THAT.
    edge case
    An input at the limit of what a function accepts: empty, one element, the largest value. Bugs gather there.
    CTest
    The test runner that comes with CMake. add_test registers a test program, and the ctest command runs them all.

    You change reverse_complement to make it faster. Does it still work? You could run the program and read its output, but you’d have to remember what the right output was, and you’d have to do it after every change. An automated test does the checking for you: it calls your code with inputs whose answers you know, compares, and fails loudly when something is wrong.

    In 30 seconds

    • A test is a program that checks results and exits with a non-zero code when one is wrong.
    • Catch2 gives you TEST_CASE, REQUIRE and CHECK, and a report that shows the values that didn’t match.
    • Compare computed floating-point results with a tolerance (WithinRel, WithinAbs, Catch::Approx), not with ==.
    • Put your code in a library, then link it into both your program and a test program; CTest runs the tests.

    A test without a framework

    A test needs no special tools: a main that calls your function, compares the results with the answers you worked out by hand, and returns non-zero when one doesn’t match. The exit code is what scripts and build tools look at (How a C++ program is built introduced it).

    The reverse complement of a DNA strand swaps each base for its partner (A with T, C with G) and reverses the order. This version forgets to reverse:

    1 file

    main.cpp
    #include <print>
    #include <string>
    #include <string_view>
    
    std::string reverse_complement(std::string_view dna) {
        std::string result;
        for (char base : dna) {
            result += std::string_view("TGCA")[std::string_view("ACGT").find(base)];
        }
        return result;
    }
    
    int failures = 0;
    
    void expect_equal(const std::string& actual, const std::string& expected) {
        if (actual != expected) {
            std::println("FAIL: got {}, expected {}", actual, expected);
            ++failures;
        }
    }
    
    int main() {
        expect_equal(reverse_complement("ATTA"), "TAAT");
        expect_equal(reverse_complement("AAC"), "GTT");
        std::println("{} failed", failures);
        return failures == 0 ? 0 : 1;
    }

    Build and run

    g++ -std=c++23 -Wall -Wextra -Wpedantic main.cpp -o app
    ./app

    Output (exits with code 1)

    FAIL: got TTG, expected GTT
    1 failed

    The first check passes even with the bug: ATTA reads the same backwards, so forgetting to reverse it changes nothing. One input can pass by luck, which is why you test several. A hand-written test works, but you soon want more: the line that failed, the values involved, a summary. A test framework gives you that.

    Catch2: TEST_CASE, REQUIRE and CHECK

    Catch2 is a widely used C++ test framework. Each TEST_CASE("name") is one test, and REQUIRE(expression) and CHECK(expression) check that an expression is true. You don’t write main: linking Catch2::Catch2WithMain adds one that runs every test case and prints a report. find_package(Catch2 3 REQUIRED) finds the installed Catch2, version 3 (CMake and libraries covered find_package).

    The first test checks a floating-point result, which takes care: double can’t hold most decimal fractions exactly (Numbers showed why), so a result that should be 0.3 may be off in the last digit. Besides ==, the test uses Catch2’s three ways to allow a small difference:

    • WithinRel(target): within a small fraction of the target’s size (by default, 100 times the precision of double).
    • WithinAbs(target, margin): within a fixed distance. Use it near zero, where a relative difference means nothing.
    • Catch::Approx(target): the older form, still common, written as value == Catch::Approx(target).

    Matchers like WithinRel go in CHECK_THAT(value, matcher) or REQUIRE_THAT. The function adds up each base’s error probability, which gives the expected number of sequencing errors in a read:

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(tests CXX)
    set(CMAKE_CXX_STANDARD 23)
    find_package(Catch2 3 REQUIRED)
    add_executable(tests tests.cpp)
    target_link_libraries(tests PRIVATE Catch2::Catch2WithMain)
    tests.cpp
    #include <span>
    
    #include <catch2/catch_approx.hpp>
    #include <catch2/catch_test_macros.hpp>
    #include <catch2/matchers/catch_matchers_floating_point.hpp>
    
    using Catch::Matchers::WithinAbs;
    using Catch::Matchers::WithinRel;
    
    double expected_errors(std::span<const double> error_probabilities) {
        double total = 0.0;
        for (double p : error_probabilities) {
            total += p;
        }
        return total;
    }
    
    TEST_CASE("expected_errors adds the probabilities") {
        double errors = expected_errors({{0.1, 0.2}});
        CHECK(errors == 0.3);
        CHECK_THAT(errors, WithinRel(0.3));
        CHECK_THAT(errors, WithinAbs(0.3, 1e-9));
        CHECK(errors == Catch::Approx(0.3));
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/tests --rng-seed 1

    Output (exits with code 42)

    Randomness seeded to: 1
    
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    tests is a Catch2 v3.7.1 host application.
    Run with -? for options
    
    -------------------------------------------------------------------------------
    expected_errors adds the probabilities
    -------------------------------------------------------------------------------
    tests.cpp:18
    ...............................................................................
    
    tests.cpp:20: FAILED:
      CHECK( errors == 0.3 )
    with expansion:
      0.30000000000000004 == 0.29999999999999999
    
    ===============================================================================
    test cases: 1 | 1 failed
    assertions: 4 | 3 passed | 1 failed

    Read the report from the top:

    • Randomness seeded to: 1 comes from the --rng-seed 1 argument, which fixes the seed for tests that use randomness. These use none, but it keeps the report the same on every run.
    • Between the dashed lines: the failing test case’s name and the line where it starts. Then tests.cpp:20: FAILED: and the check as you wrote it.
    • with expansion: the same check with the values filled in. This is what a hand-written test lacks: 0.1 + 0.2 is one step above the double closest to 0.3.
    • The summary: one test case failed; of its 4 assertions, 3 passed. The program exits with code 42, Catch2’s code for “some tests failed”.

    All four checks ran because they’re CHECKs. A failing REQUIRE stops its test case, so the three tolerant checks after it wouldn’t have run.

    Key ideaREQUIRE or CHECK

    Use REQUIRE when the rest of the test case makes no sense after a failure, such as checking that a vector isn’t empty before reading its first element. Use CHECK for independent checks, so one run shows every failure.

    Shared setup and errors: SECTION and REQUIRE_THROWS_AS

    Several checks often start from the same data. Inside a TEST_CASE, each SECTION is a separate path: Catch2 runs the test case once per section, from the top, so every section gets a fresh copy of the setup. And a function that throws on bad input (Exceptions) should be tested for that too: REQUIRE_THROWS_AS(expression, type) passes when the expression throws an exception of that type (or one derived from it).

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(tests CXX)
    set(CMAKE_CXX_STANDARD 23)
    find_package(Catch2 3 REQUIRED)
    add_executable(tests tests.cpp)
    target_link_libraries(tests PRIVATE Catch2::Catch2WithMain)
    tests.cpp
    #include <stdexcept>
    #include <string>
    #include <string_view>
    
    #include <catch2/catch_test_macros.hpp>
    
    int base_code(char base) {
        auto index = std::string_view("ACGT").find(base);
        if (index == std::string_view::npos) {
            throw std::invalid_argument("not a DNA base");
        }
        return static_cast<int>(index);
    }
    
    TEST_CASE("base_code") {
        std::string read = "GATTACA";
    
        SECTION("each base has a code") {
            REQUIRE(base_code(read[0]) == 2);
        }
        SECTION("other letters throw") {
            read[0] = 'N';
            REQUIRE_THROWS_AS(base_code(read[0]), std::invalid_argument);
        }
        SECTION("each section starts from the same read") {
            REQUIRE(read[0] == 'G');
        }
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/tests --rng-seed 1

    Output

    Randomness seeded to: 1
    ===============================================================================
    All tests passed (3 assertions in 1 test case)

    The third section sees G, although the second changed read[0] to N: each run built a new read.

    A library, an app and tests

    So far the function lived in the test file. In a real project, the code goes in a library, and both the program and the test program link it, as in CMake and libraries. Then the tests check exactly the code the program runs:

    5 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(gc CXX)
    set(CMAKE_CXX_STANDARD 23)
    find_package(Catch2 3 REQUIRED)
    enable_testing()
    
    add_library(dna src/dna.cpp)
    target_include_directories(dna PUBLIC include)
    
    add_executable(gc src/main.cpp)
    target_link_libraries(gc PRIVATE dna)
    
    add_executable(tests tests/test_dna.cpp)
    target_link_libraries(tests PRIVATE dna Catch2::Catch2WithMain)
    add_test(NAME dna_tests COMMAND tests)
    include/dna.h
    #pragma once
    
    #include <string_view>
    
    double gc_fraction(std::string_view dna);
    src/dna.cpp
    #include "dna.h"
    
    double gc_fraction(std::string_view dna) {
        if (dna.empty()) {
            return 0.0;
        }
        int gc = 0;
        for (char base : dna) {
            gc += base == 'G' || base == 'C';
        }
        return static_cast<double>(gc) / static_cast<double>(dna.size());
    }
    src/main.cpp
    #include <print>
    
    #include "dna.h"
    
    int main() {
        std::println("{:.2f}", gc_fraction("GATTACA"));
    }
    tests/test_dna.cpp
    #include <catch2/catch_test_macros.hpp>
    
    #include "dna.h"
    
    TEST_CASE("gc_fraction") {
        REQUIRE(gc_fraction("GGCC") == 1.0);
        REQUIRE(gc_fraction("ATGC") == 0.5);
        REQUIRE(gc_fraction("") == 0.0);
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/tests --rng-seed 1

    Output

    Randomness seeded to: 1
    ===============================================================================
    All tests passed (3 assertions in 1 test case)

    == is safe in this test: 1, 0.5 and 0 are exact in a double, and one division gives an exact answer when there is one.

    enable_testing() turns on CTest, and add_test registers the tests program under the name dna_tests. After a build, ctest --test-dir build --output-on-failure runs every registered test program, marks each passed or failed by its exit code, and prints the report of any that failed. With several test programs, that one command runs them all; it’s what a build server calls. (This site runs build/tests directly, so the output shown is Catch2’s.)

    What to test

    Test the ordinary cases, then the edge cases, where most bugs are:

    • Empty input: an empty string, an empty vector. gc_fraction above checks for it, because 0.0 / 0.0 gives NaN (not a number), not 0.0.
    • One element, and inputs exactly at a limit: a read exactly k bases long when you count k-mers.
    • The largest values: sums that could overflow an int, lengths near the maximum.
    • Bad input: characters that aren’t bases, negative counts. Test that they’re rejected.

    Run your tests with the sanitizers on, as every example on this site is. Then a test that touches undefined behavior fails even when the result happens to look right. Here the test for an empty list of quality scores divides by zero, and UndefinedBehaviorSanitizer stops the run:

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(tests CXX)
    set(CMAKE_CXX_STANDARD 23)
    find_package(Catch2 3 REQUIRED)
    add_executable(tests tests.cpp)
    target_link_libraries(tests PRIVATE Catch2::Catch2WithMain)
    tests.cpp
    #include <span>
    #include <vector>
    
    #include <catch2/catch_test_macros.hpp>
    
    int mean_quality(std::span<const int> scores) {
        int total = 0;
        for (int q : scores) {
            total += q;
        }
        return total / static_cast<int>(scores.size());
    }
    
    TEST_CASE("mean_quality") {
        std::vector<int> scores = {30, 40, 20};
        REQUIRE(mean_quality(scores) == 30);
        REQUIRE(mean_quality({}) == 0);
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/tests

    This fails when it runs

    tests.cpp:11:18: runtime error: division by zero

    Without the sanitizer, dividing an integer by zero crashes the program on x86-64, but undefined behavior doesn’t promise even that. Decide what an empty list means (here 0, or a std::optional with no value) and check for it first.

    Which one should I use?

    WhatWhenWhyHow
    A plain test programA tiny project, or a place where you can’t add a library.No dependencies; the exit code is all a build tool needs.main that checks and returns non-zero
    REQUIRE / CHECKREQUIRE when later checks depend on this one; CHECK otherwise.REQUIRE stops before bad data is used; CHECK reports every failure in one run.REQUIRE(v.size() == 3);, CHECK(f("") == 0);
    WithinRel / WithinAbsAny floating-point result.Rounding makes == fail on correct code.CHECK_THAT(x, WithinRel(0.3));
    CTestMore than one test program, or a build server.One command runs them all.enable_testing(), add_test(…), ctest

    Rule of thumb: put the code in a library, test it with Catch2 under the sanitizers, and add a test for every bug you fix, so it can’t come back.

    Under the hood

    TEST_CASE is a macro. It declares a function with a generated name for the body that follows, and a global object whose constructor adds that function, its name and its file and line to Catch2’s list of tests. GCC and Clang build global objects before main runs, so by the time the main from Catch2WithMain starts, every test case in every linked file is on the list. That main reads the command line (you can pass a test name to run one test), runs the tests and returns 0 when all pass, or 42 when any fails.

    REQUIRE(a == b) is a macro too: it keeps both values so it can print them in the expansion. When a REQUIRE fails, Catch2 throws an internal exception to leave the test case; a CHECK records the failure and goes on.

    Common pitfalls

    Linking Catch2 without its main

    Catch2 comes as two CMake targets: Catch2::Catch2, the framework, and Catch2::Catch2WithMain, which adds a main. Link only the first and your test program has no main:

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(tests CXX)
    set(CMAKE_CXX_STANDARD 23)
    find_package(Catch2 3 REQUIRED)
    add_executable(tests tests.cpp)
    target_link_libraries(tests PRIVATE Catch2::Catch2)
    tests.cpp
    #include <catch2/catch_test_macros.hpp>
    
    TEST_CASE("square") {
        REQUIRE(3 * 3 == 9);
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/tests

    The compiler rejects this

    ld: /usr/lib/gcc/x86_64-linux-gnu/15/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
    (.text+0x1b): undefined reference to `main'
    collect2: error: ld returned 1 exit status

    Link Catch2::Catch2WithMain instead. Use Catch2::Catch2 only when you write your own main, for example to set up something once for all tests.

    A test that can’t fail

    A test that only calls the function, or compares it with a value you copied from its own output, passes whatever the code does. Work out the expected answer independently, by hand or from a trusted tool, and watch each new test fail once (break the code on purpose) to see that it checks something.

    Try it yourself

    Try it yourself

    kmer_count returns how many k-mers (substrings of length k) a read has. The test program checks one ordinary case and passes. Add tests for the edge cases, see which one fails, then fix kmer_count.

    #include <cstddef>
    #include <print>
    #include <string_view>
    
    std::size_t kmer_count(std::string_view sequence, std::size_t k) {
        return sequence.size() - k + 1;
    }
    
    int main() {
        int failures = 0;
        if (kmer_count("GATTACA", 3) != 5) {
            std::println("FAIL: GATTACA, k = 3");
            ++failures;
        }
        std::println("{} failed", failures);
        return failures == 0 ? 0 : 1;
    }

    Expected output

    0 failed
    Show a hint

    Ask what kmer_count should return for a read exactly k long (1), one base shorter than k (0), and an empty read (0). sequence.size() and k are unsigned, so sequence.size() - k wraps around to a huge number when k is bigger.

    Show a solution
    #include <cstddef>
    #include <print>
    #include <string_view>
    
    std::size_t kmer_count(std::string_view sequence, std::size_t k) {
        if (k > sequence.size()) {
            return 0;
        }
        return sequence.size() - k + 1;
    }
    
    int main() {
        int failures = 0;
        auto expect = [&failures](std::size_t actual, std::size_t expected) {
            if (actual != expected) {
                std::println("FAIL: got {}, expected {}", actual, expected);
                ++failures;
            }
        };
        expect(kmer_count("GATTACA", 3), 5);
        expect(kmer_count("GAT", 3), 1);
        expect(kmer_count("GA", 3), 0);
        expect(kmer_count("", 3), 0);
        std::println("{} failed", failures);
        return failures == 0 ? 0 : 1;
    }

    std::size_t can't be negative: 2 - 3 wraps around to the largest std::size_t, and adding 1 wraps again to 0, so a read one base too short passes by luck. An empty read gives a huge number and fails. Checking k > sequence.size() first returns 0 for every read shorter than k. Only the tests at the edges find this bug.

    Saved in this browser only.