skip to content

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%

answer

  1. a derived class per case
  2. one object per partial run
  3. persistent means once per case
  4. the body is const

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.

solid answer

~40 s

`TEST_CASE_METHOD(Fixture, name, tags)` generates a uniquely named class derived from `Fixture` and makes the test body one of its member functions, so protected members are usable directly. An instance is created **for every partial run**: a case with three leaf sections constructs the fixture three times, which gives each section fresh state exactly as plain sections do. `TEST_CASE_PERSISTENT_FIXTURE`, added in Catch2 3.7.0, creates **one** instance before the case starts and destroys it after the case ends, so an expensive object, such as a graphics device, a database connection or a loaded file, is built once. The cost is coupling: later sections see what earlier ones did, and running one section alone changes the state it starts from. Its body is a `const` member function, so any member the test mutates must be declared `mutable`.

code

cpp · 24 lines
cpp
#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <vector>

struct StackFixture {
    StackFixture() { std::cout << "fixture #" << ++constructed << '\n'; }
    static inline int constructed = 0;
    std::vector<int> stack{1, 2, 3};
};

TEST_CASE_METHOD(StackFixture, "fixture per partial run", "[fixture]") {
    SECTION("push") { stack.push_back(4); REQUIRE(stack.size() == 4u); }
    SECTION("pop")  { stack.pop_back();   REQUIRE(stack.size() == 2u); }
}

struct Persistent {
    Persistent() { std::cout << "persistent constructed\n"; }
    mutable std::vector<int> stack{1, 2, 3};
};

TEST_CASE_PERSISTENT_FIXTURE(Persistent, "one fixture for all partial runs", "[fixture]") {
    SECTION("pop")       { stack.pop_back(); REQUIRE(stack.size() == 2u); }
    SECTION("pop again") { stack.pop_back(); REQUIRE(stack.size() == 1u); }
}

go deeper

for a junior

Recall that TEST_CASE_METHOD takes a fixture class and that the test body can use its members directly, as if it were a member function.

for a middle

Explain that the fixture is rebuilt for every partial run, count constructions for a case with sections, and say why protected members are accessible.

for a senior

Decide when one fixture per case is worth the coupling: measure setup cost, keep mutation in mutable members few and named, and warn that section filters change outcomes.

for a principal

Set a team default of fresh state per partial run, with persistent fixtures as a reviewed exception for expensive, read-mostly resources such as devices and connections.

## Fixtures in a section-first framework Catch2 prefers sections for shared setup, but it also supports class-based fixtures when a group of test cases needs the same members or helper functions. The fixture-and-test-class style of the other major C++ framework is taught with that framework; here the question is how Catch2's own macros create and destroy the fixture object, and how that interacts with sections. ## The three non-templated fixture macros | Macro | What the body is | Fixture instances | |---|---|---| | `TEST_CASE_METHOD(Fixture, name, tags)` | A member function of a uniquely named class derived from `Fixture` | One per partial run | | `METHOD_AS_TEST_CASE(Class::method, name, tags)` | The existing member function itself | One per partial run | | `TEST_CASE_PERSISTENT_FIXTURE(Fixture, name, tags)` | A `const` member function of a class derived from `Fixture` | One per test case | `SCENARIO_METHOD` is the BDD spelling of `TEST_CASE_METHOD`, and templated variants exist for type-parameterised fixtures. ## TEST_CASE_METHOD: one object per partial run A **partial run** is one pass through the test case, entering one leaf section. Catch2's fixture documentation states that an instance of the derived class is created for every partial run. With a stack fixture and two leaf sections: ```cpp struct StackFixture { StackFixture() { ++constructed; } static inline int constructed = 0; std::vector<int> stack{1, 2, 3}; }; TEST_CASE_METHOD(StackFixture, "fixture per partial run", "[fixture]") { SECTION("push") { stack.push_back(4); REQUIRE(stack.size() == 4u); } SECTION("pop") { stack.pop_back(); REQUIRE(stack.size() == 2u); } } ``` the constructor runs twice and each section starts from `{1, 2, 3}`. Because the test body is a member of a class derived from the fixture, it can use `protected` members and helpers without qualification. A static member, like the counter above, is shared by every instance and is not reset. ## TEST_CASE_PERSISTENT_FIXTURE: one object per case This macro, introduced in **Catch2 3.7.0**, keeps one fixture instance for the whole test case. The fixture is constructed just before the case begins and destroyed just after it ends, however many partial runs happen in between. The documentation names two uses: 1. Cutting run time when setup and teardown are expensive, for example creating a graphics device, connecting to a database or loading a large file. 2. Reusing a result from one partial run in the next one. The test function is a **`const` member function**, deliberately, so that mutation is visible in the code. Mutating a non-`mutable` member fails to compile; clang 21 reported: ```plaintext error: 'this' argument to member function 'pop_back' has type 'const std::vector<int>', but function is not marked const ``` Declaring the member `mutable` makes the intent to carry state across partial runs explicit. ## The price of persistence - **Sections stop being independent.** A second section sees what the first left behind, so the order of sections becomes part of the test's meaning. - **Selecting one section changes the result.** Running a single section from the command line skips the ones that would have prepared the shared state. - **A failure can cascade.** If one partial run leaves the fixture half-modified, later ones start from that state. - **Scope is one test case.** The object is not shared across different test cases; sharing across cases needs something outside the fixture, such as a lazily initialised static, with all the coupling that implies. ## Templated fixtures and teardown - **Templated fixtures** use `TEMPLATE_TEST_CASE_METHOD(Fixture, name, tags, types...)`, which instantiates a class template fixture once per listed type; the fixture's members are then reached through the dependent base, as in `Fixture<TestType>::member`. The same per-partial-run lifetime applies. - **Teardown** is the fixture's destructor. With `TEST_CASE_METHOD` it runs at the end of every partial run, so a temporary directory or a mock server started in the constructor is cleaned up between sections. With the persistent macro it runs once, after the last partial run. - **An exception from the constructor** fails the test case before any section is entered. In a Catch2 3.16.1 run of a two-section case whose fixture constructor threw, the constructor ran once, the failure was reported against the test case as an unexpected exception, and neither section ran. ## Choosing between them - Default to plain sections, or `TEST_CASE_METHOD` when several cases share members and helpers. Fresh state per partial run is what makes each failure local. - Use `TEST_CASE_PERSISTENT_FIXTURE` when construction dominates the run time and the object is effectively read-only during the test, or when the case is intentionally a sequence of steps. - Keep mutation in a persistent fixture rare and visible: few `mutable` members, named for what they carry.

  • Why can a Catch2 TEST_CASE_METHOD body use the fixture's protected members without qualification?
    The macro generates a uniquely named class that inherits from the fixture and defines the test body as a member function of that derived class. A derived class's member functions can access the base's `protected` members, so a member such as `stack`, or a protected helper function, is used directly, without `this->` or an object name.
  • What breaks when a single section of a Catch2 TEST_CASE_PERSISTENT_FIXTURE case is run on its own?
    The state it expects may never be built. With one fixture per case, later sections rely on what earlier partial runs did to `mutable` members. Selecting only the second section skips the first, so the fixture reaches it in its freshly constructed state and assertions written for the accumulated state fail or, worse, pass for the wrong reason.

  • TEST_CASE_METHOD constructs its fixture once per test case.
  • A Catch2 persistent fixture is shared across every test case that names it.
  • Members of a persistent fixture can be mutated without mutable.
  • Catch2 has no class-based fixtures, only sections.
  • TEST_CASE_PERSISTENT_FIXTURE has existed since Catch2 2.

Assumes Catch2 3; TEST_CASE_PERSISTENT_FIXTURE was introduced in Catch2 3.7.0 and does not exist in Catch2 2.