Fixtures
A fixture is shared setup and teardown for a group of tests: a temp directory, a parsed config, a fake clock. In GoogleTest that is a class with SetUp/TearDown used by TEST_F. In Catch2 it is often a SECTION or a RAII object at the top of a TEST_CASE.
Detailed Explanation
Tests that each open a database and insert the same seed waste time and drift. A fixture builds the seed once per test (not once per process — isolation matters) and releases it after. GoogleTest constructs a fresh fixture object for every TEST_F. SetUp runs after the constructor, the test runs, TearDown runs, then the destructor. Prefer putting resources in members that clean themselves (RAII) and leave TearDown empty.
SetUpTestSuite / TearDownTestSuite (static) run once per suite. Use them for an expensive immutable asset (a large file you read-only). Do not use them for mutable state two tests will fight over.
Catch2 re-runs the TEST_CASE body for each SECTION, which is fixture-by-re-execution. Catch2 also has TEST_CASE_METHOD(Fixture, "name") if you want a class.
A good fixture is fast, isolated, and obvious. A bad fixture is a hidden global, a shared server port, or a 30-second SetUp. If setup is slow, split the suite or use a process-wide read-only asset.
Dependencies you cannot construct in isolation (a real payment API) do not belong in a unit fixture. That is an integration test with a different harness.
Naming: the fixture class is the suite name in TEST_F(Fixture, Case). Keep the class small. If two groups need different seeds, use two fixtures.
Test base in GoogleTest should be inherited publicly. Multiple inheritance of fixtures is possible and usually a sign you wanted composition (a member TempDir dir_;).
Code Examples
#include <cstdio>
#include <fstream>
#include <gtest/gtest.h>
#include <string>
class FileFix : public ::testing::Test {
protected:
void SetUp() override {
path_ = "cpp-glossary-fixture.txt";
std::ofstream(path_) << "ok\n";
}
void TearDown() override { std::remove(path_.c_str()); }
std::string path_;
};
TEST_F(FileFix, Reads) {
std::ifstream in(path_);
std::string s;
in >> s;
EXPECT_EQ(s, "ok");
}#include <catch2/catch_test_macros.hpp>
#include <vector>
TEST_CASE("fixture via section") {
std::vector<int> v{1, 2};
SECTION("size") { REQUIRE(v.size() == 2); }
SECTION("push") {
v.push_back(3);
REQUIRE(v.size() == 3);
}
}Common Gotchas
Shared mutable suite state
`SetUpTestSuite` plus a static `vector` that tests push into will flake under shuffle.
Forgetting to clean temp files
the next run sees stale data. RAII a path, or `TearDown` even on assertion failure (GoogleTest still runs it).
Constructor failures in a fixture
GoogleTest reports them; prefer `SetUp` for things that can fail with `ASSERT`.
Catch2 sections re-run setup
a slow constructor at the top of the `TEST_CASE` runs once per section.