skip to content

Catch2

The header-first C++ framework whose SECTIONs re-run a case per branch and whose REQUIRE decomposes a plain expression. Asked as the lighter alternative to GoogleTest.

on this pageshow

explore

questions

17

In Catch2, what is the difference between REQUIRE and CHECK when the asserted expression is false?

level: juniorimportance: must knowfreq 50%

answer

  1. both fail the test case
  2. one aborts, one continues
  3. aborting is done by throwing
  4. guard what later lines depend on

basics

~20 s

Both record a failure and fail the test case. REQUIRE then aborts the current run, while CHECK continues so later assertions still report. Use REQUIRE where later code depends on the condition and CHECK for independent facts.

solid answer

~40 s

`REQUIRE(expr)` and `CHECK(expr)` evaluate the same expression and report it the same way, operands included. The difference is what happens after a failure. `REQUIRE` aborts the current run of the test case, so nothing after it executes; `CHECK` records the failure and carries on, so a series of independent checks all report in one run. Either way the test case is marked failed. The rule of thumb: `REQUIRE` guards preconditions that later lines rely on, such as a container being non-empty before indexing it, and `CHECK` covers independent observations, such as several properties of one result. If the expression throws, both catch the exception and count it as a failure. `REQUIRE_FALSE` and `CHECK_FALSE` assert that something is false, because a leading `!` cannot be decomposed.

code

cpp · 18 lines
cpp
#include <catch2/catch_test_macros.hpp>
#include <cmath>
#include <iostream>

struct Point { double x, y; };
double distance(Point a, Point b) { return std::hypot(b.x - a.x, b.y - a.y); }

TEST_CASE("CHECK keeps going", "[geometry]") {
    CHECK(distance({0, 0}, {3, 4}) == 4.0);
    CHECK(distance({0, 0}, {0, 0}) == 1.0);
    std::cout << "reached the end of the CHECK case\n";
}

TEST_CASE("REQUIRE stops", "[geometry]") {
    REQUIRE(distance({0, 0}, {3, 4}) == 4.0);
    std::cout << "never printed\n";
    REQUIRE(distance({0, 0}, {0, 0}) == 1.0);
}

go deeper

for a junior

Recall that REQUIRE stops the test case at the first failure and CHECK keeps going, and that both make the test case fail.

for a middle

Explain that REQUIRE aborts by throwing, what that means for catch-all blocks and destructors, and how an exception from the expression is reported.

for a senior

Structure assertions so a single run diagnoses as much as possible: REQUIRE for the preconditions later lines depend on, CHECK for every independent fact after them.

for a principal

Set a review norm for assertion choice, so failures arrive as a complete picture rather than one rebuild per broken property.

## Two families, one expression syntax Catch2 has no `_EQUALS` or `_GREATER_THAN` macros. It takes an ordinary C++ comparison, `REQUIRE(a == b)`, and reports both sides when it fails. Almost every assertion comes in two forms that differ only in **what happens after a failure**: | Fatal form | Continuing form | Checks | |---|---|---| | `REQUIRE(expr)` | `CHECK(expr)` | the expression is true | | `REQUIRE_FALSE(expr)` | `CHECK_FALSE(expr)` | the expression is false | | `REQUIRE_THROWS_AS(expr, T)` | `CHECK_THROWS_AS(expr, T)` | an exception of type `T` | | `REQUIRE_THAT(value, matcher)` | `CHECK_THAT(value, matcher)` | a matcher accepts the value | In Catch2 3 they come from `catch2/catch_test_macros.hpp` (the matcher forms also need the matcher headers). ## What a failure does - **Both** record the failed assertion with its source line and expansion, and **both** mark the test case as failed. A `CHECK` failure is not a warning. - **`REQUIRE` aborts** the current run of the test case: the rest of the function does not execute. With sections, only the current run ends; the next run for the next section still happens. - **`CHECK` continues** with the next statement, so every independent assertion reports in one go. A run with a distance function shows the difference: ```cpp TEST_CASE("CHECK keeps going", "[geometry]") { CHECK(distance({0, 0}, {3, 4}) == 4.0); // fails: 5.0 == 4.0 CHECK(distance({0, 0}, {0, 0}) == 1.0); // fails: 0.0 == 1.0 std::cout << "reached the end\n"; // printed } TEST_CASE("REQUIRE stops", "[geometry]") { REQUIRE(distance({0, 0}, {3, 4}) == 4.0); // fails: 5.0 == 4.0 std::cout << "never printed\n"; // not reached } ``` The first case reports two failures and prints its last line; the second reports one failure and stops. ## How REQUIRE aborts `REQUIRE` stops the test by **throwing** an internal exception type after the failure has been recorded. Two consequences follow: 1. A `catch (...)` block around a `REQUIRE` swallows the abort. The failure is still recorded and the test case still fails, but the lines after the `try` block keep running, which can then crash on the very state the `REQUIRE` was guarding. 2. A failing `REQUIRE` inside a destructor, which is `noexcept` by default, or inside any other `noexcept` function throws out of a function that may not throw, so the program terminates. In a run with libc++, the binary printed `terminating due to uncaught exception of type Catch::TestFailureException` and aborted, taking every remaining test with it. A `CHECK` is the safe form there. ## Exceptions from the expression If evaluating the expression itself throws, both forms catch the exception, report it with its message, and count the assertion as failed. A degenerate triangle passed to an area function that throws `std::invalid_argument` therefore shows up as: ```plaintext a.cpp:16: FAILED: REQUIRE( triangleArea({0, 0}, {1, 1}, {2, 2}) > 0.0 ) due to unexpected exception with message: degenerate triangle ``` An unexpected exception in a `CHECK` does not abort the run either. ## Asserting that something is false The decomposer cannot see through a leading `!`. For a type that converts to `bool`, such as a status object, `REQUIRE_FALSE(status)` asserts it is false and can still print its value. For a plain `bool` variable there is nothing extra to print, so `CHECK(!ok)` and `CHECK_FALSE(ok)` say the same thing. ## What the summary counts The run summary counts assertions that actually executed. In the run above, the two cases produced `assertions: 3 | 3 failed`: two from the `CHECK` case and one from the `REQUIRE` case, whose second assertion never ran. That has practical consequences: - A `REQUIRE` that fails early **hides** every later assertion in that run, so the summary understates how much is broken. - After a fix, a previously hidden assertion can fail next, which looks like a new regression but was there all along. - Comparing assertion counts between two runs is only meaningful when both ran to the same point. The test-case line, `test cases: 2 | 2 failed`, is the same for both forms: one failed assertion of either kind is enough to fail its case. ## Choosing between them - **`REQUIRE` for preconditions**: a pointer is non-null before it is dereferenced, a vector is non-empty before `front()`, a parse succeeded before its result is inspected. Continuing after these would only produce noise or undefined behaviour. - **`CHECK` for independent facts**: the x and y of a computed point, every field of a parsed record, every element of a small table. One run then shows the whole picture. - **Mix them**: one `REQUIRE` that the result exists, followed by several `CHECK`s on its contents, is the most common healthy shape. - **Avoid `REQUIRE` everywhere by habit**: the first failure hides the rest, and fixing one at a time costs a build per failure.

  • What happens when a Catch2 REQUIRE fails inside a try block with a catch (...) handler?
    The failure is recorded first, so the test case still fails. But `REQUIRE` aborts by throwing an internal exception, and `catch (...)` swallows it, so execution continues after the `try` block. The lines that the `REQUIRE` was meant to protect then run anyway. Catch specific exception types in test code, or keep assertions outside catch-all blocks.
  • Does a failed Catch2 CHECK in one section stop the other sections of the test case?
    No. A `CHECK` does not even stop its own section; execution continues to the next statement. A `REQUIRE` ends only the current run of the test case, and Catch2 still re-enters the case for each remaining section. In both cases the test case is reported as failed.

  • A failed CHECK is only a warning; the test case still passes.
  • REQUIRE stops the entire test binary on failure.
  • CHECK should be avoided because it hides failures.
  • An exception thrown inside REQUIRE's expression crashes the test run.
  • REQUIRE(!status) prints the value of status when it fails.
open as a page

In Catch2, what do the name and tags arguments of TEST_CASE do, and how do tags decide which tests run?

level: juniorimportance: must knowfreq 45%

basics

~20 s

TEST_CASE takes a free-form quoted name and an optional string of bracketed tags such as "[stack][fast]". Name plus tags must be unique in the binary; tags group cases for selection, and a [.] tag hides one from the default run.

open as a page

In Catch2 3, how do you compare a computed double against an expected value, and when do WithinRel and WithinAbs differ?

level: middleimportance: must knowfreq 40%

basics

~20 s

Use REQUIRE_THAT with Catch::Matchers::WithinRel or WithinAbs instead of ==. WithinRel scales its tolerance with the values' magnitude, defaulting to 100 machine epsilons; WithinAbs uses a fixed margin, which is what works when the expected value is zero.

open as a page

In Catch2, how does a TEST_CASE containing several SECTIONs execute, and why does each section start from fresh setup?

level: middleimportance: must knowfreq 50%

basics

~20 s

Catch2 runs a TEST_CASE once per leaf SECTION, each time from the top. Each run repeats the setup and enters exactly one leaf, so every section sees freshly built locals; a parent section is entered once per leaf beneath it.

open as a page

How do you run only some Catch2 tests from the command line and write JUnit XML for CI in the same run?

level: juniorimportance: should knowfreq 30%

basics

~20 s

Pass a test spec, such as a name, "area*" or "[geometry]~[slow]", to the test binary, and choose reporters with -r. Since Catch2 3.0.1, several can run at once: -r console -r junit::out=results.xml writes readable output and a JUnit file.

open as a page

In Catch2, how do INFO and CAPTURE add context to a failing assertion, and how long does each message stay attached?

level: middleimportance: should knowfreq 30%

basics

~20 s

INFO streams a message and CAPTURE logs "expression := value"; both attach to every assertion in their enclosing scope and print only beside failures. Each disappears at the end of its block, so loop context resets per iteration.

open as a page

In Catch2, how do REQUIRE_THROWS_AS, REQUIRE_THROWS_WITH and REQUIRE_THROWS_MATCHES differ when testing that a degenerate triangle throws?

level: middleimportance: should knowfreq 35%

basics

~20 s

REQUIRE_THROWS_AS checks the exception's type, accepting derived types. REQUIRE_THROWS_WITH checks its message as a string, exactly or through a string matcher. REQUIRE_THROWS_MATCHES checks the type and then applies a matcher, such as Message, to the caught exception.

open as a page

In Catch2, how does GENERATE run one TEST_CASE once per value, and what do the take, filter and range adaptors do?

level: middleimportance: should knowfreq 25%

basics

~20 s

GENERATE(1, 3, 5) makes Catch2 enter the test case once per value, and several GENERATE calls give their cartesian product. Adaptors build sequences: range(a, b) stops before b, filter keeps matching values, take keeps the first n.

open as a page

In Catch2, how do SCENARIO, GIVEN, WHEN and THEN map onto TEST_CASE and SECTION, and where does AND_WHEN go?

level: middleimportance: should knowfreq 30%

basics

~20 s

SCENARIO is a TEST_CASE whose name gains a "Scenario: " prefix, and GIVEN, WHEN and THEN are sections with prefixed names. AND_GIVEN, AND_WHEN and AND_THEN go inside the clause they depend on; Catch2 enforces no ordering.

open as a page

In Catch2, how does TEMPLATE_TEST_CASE run one test body over several types, and what trips people up when listing those types?

level: middleimportance: should knowfreq 25%

basics

~20 s

TEMPLATE_TEST_CASE(name, tags, types...) registers one test case per listed type, named "name - type", with the current type available as TestType. A type containing a comma must be wrapped in parentheses, and Catch2 3 needs catch_template_test_macros.hpp.

open as a page

Why does REQUIRE(p.x == 3.0 && p.y == 4.0) fail to compile in Catch2, and what do you lose by wrapping it in parentheses?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Catch2 decomposes an assertion through overloaded operators to print both operands, and deliberately rejects && and || with a static_assert. Extra parentheses compile but turn the expression into one bool, so a failure prints only "false"; split it instead.

open as a page

How does Catch2's catch_discover_tests register test cases with CTest, and why can it fail the build or silently miss tests?

level: seniorimportance: should knowfreq 30%

basics

~20 s

catch_discover_tests, from Catch2's Catch.cmake, runs the built binary with --list-tests and adds one CTest test per TEST_CASE. Listing runs after the build by default, so a binary that cannot list fails the build; hidden cases need a TEST_SPEC.

open as a page

When migrating a CMake project from Catch2 v2's single catch.hpp to Catch2 v3, what changes in the includes, the main function and the link targets?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Catch2 v3 is a compiled static library with per-feature headers. Replace catch.hpp with catch_test_macros.hpp and the feature headers you use, delete the CATCH_CONFIG_MAIN file, and link Catch2::Catch2WithMain, or Catch2::Catch2 plus your own main.

open as a page

In Catch2, how often is a TEST_CASE_METHOD fixture constructed when its case has sections, and when would you reach for TEST_CASE_PERSISTENT_FIXTURE instead?

level: seniorimportance: should knowfreq 25%

basics

~20 s

TEST_CASE_METHOD builds a fresh fixture for every partial run, once per leaf section. TEST_CASE_PERSISTENT_FIXTURE, added in Catch2 3.7.0, builds one fixture for the whole case; it suits expensive setup, but state then carries between sections and members must be mutable.

open as a page

A Catch2 test wraps a stack pop in SECTION("pop once") inside a three-iteration for loop, yet the section body runs only once. Why, and how do you fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Catch2 identifies a section by name and source location, so every iteration meets one section: it runs once, later iterations skip it, and it is then complete. DYNAMIC_SECTION("pop with i = " << i) makes one section, and one run, per iteration.

open as a page

In Catch2 3, how do you write a BENCHMARK inside a test case, and why should the benchmarked block return its result?

level: middleimportance: nice to knowfreq 15%

basics

~20 s

Include catch2/benchmark/catch_benchmark.hpp and write BENCHMARK("name") { return compute(); }; inside a TEST_CASE. The block is a lambda, so it needs a semicolon, and returning the result is the documented way to keep the compiler from optimising the work away.

open as a page

A Catch2 test calls GENERATE(1, 2), then has SECTION one with GENERATE(-3, -2) and SECTION two with GENERATE(4, 5, 6). How many passes run, and why?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Ten passes. GENERATE acts as an implicit section reaching to the end of its scope, so each outer value replays every leaf below it: section one runs 2 x 2 = 4 times, section two 2 x 3 = 6.

open as a page