skip to content

In GoogleTest, when is SetUpTestSuite worth using over per-test SetUp, and what goes wrong when tests share the resource it creates?

level: seniorimportance: should knowfreq 38%

answer

  1. static members, set up once
  2. expensive and read-only
  3. order is not guaranteed
  4. derived fixtures call it again

basics

~10 s

Use static SetUpTestSuite and TearDownTestSuite when a resource is expensive and the tests only read it. Tests that modify it become order-dependent, and failures appear or vanish under filtering and shuffling.

solid answer

~40 s

`static void SetUpTestSuite()` runs before the first test of the suite and `static void TearDownTestSuite()` after the last, around **static** members holding a resource every test can see, such as a seeded snapshot of the store that costs seconds to build. It pays off only when the resource is **expensive** and tests treat it as **read-only** or restore it. A test that mutates it makes later tests depend on order, which `--gtest_shuffle` and filters change, so failures come and go. Two traps from the docs: `SetUpTestSuite()` may run **more than once** when derived fixtures exist, so guard the allocation; and a failure inside it makes GoogleTest **skip** every test in the suite, report the suite as failed in `SetUpTestSuite or TearDownTestSuite`, and still call `TearDownTestSuite()`. Program-wide set-up uses a `testing::Environment` instead.

code

cpp · 35 lines
cpp
#include <gtest/gtest.h>
#include <cstdio>
#include <map>
#include <string>

// Stand-in for an expensive resource, such as a seeded snapshot of a store.
using Snapshot = std::map<std::string, std::string>;

class SnapshotTest : public testing::Test {
 public:
  static void SetUpTestSuite() {
    std::puts("SetUpTestSuite");
    if (snapshot_ == nullptr) snapshot_ = new Snapshot{{"user", "ada"}};
  }
  static void TearDownTestSuite() {
    std::puts("TearDownTestSuite");
    delete snapshot_;
    snapshot_ = nullptr;
  }

 protected:
  static Snapshot* snapshot_;
};

Snapshot* SnapshotTest::snapshot_ = nullptr;

TEST_F(SnapshotTest, ReadsUser) { EXPECT_EQ(snapshot_->at("user"), "ada"); }
TEST_F(SnapshotTest, HasOneKey) { EXPECT_EQ(snapshot_->size(), 1u); }

class BrokenSnapshotTest : public testing::Test {
 public:
  static void SetUpTestSuite() { ADD_FAILURE() << "cannot seed snapshot"; }
};

TEST_F(BrokenSnapshotTest, NeverRuns) { std::puts("body ran"); }

go deeper

for a junior

Recall that SetUpTestSuite and TearDownTestSuite are static and run once around a suite, unlike SetUp and TearDown.

for a middle

Explain the three scopes, test, suite and program, and why shared resources must be read-only or restored.

for a senior

Diagnose order-dependent failures caused by shared suite state, the repeated call from derived fixtures, and the skip behaviour when suite set-up fails.

for a principal

Weigh test-suite speed against isolation and decide which resources a team may share across tests, and how that sharing is verified in CI.

## Three scopes of set-up GoogleTest supports set-up and tear-down at three scopes: | Scope | Hooks | Runs | |---|---|---| | test | constructor, `SetUp()`, `TearDown()`, destructor | around every test | | test suite | `static void SetUpTestSuite()`, `static void TearDownTestSuite()` | before the first and after the last test of the suite | | program | a `testing::Environment` subclass's `SetUp()` and `TearDown()` | once around all tests, when registered with `AddGlobalTestEnvironment` | The per-test scope is the default because it keeps tests independent. The suite scope exists for one situation: a resource that is **too expensive to build for every test** and that tests can **share without changing it**. ## Writing suite-level set-up 1. Declare `static` members in the fixture to hold the shared resource, typically a pointer. 2. Define them outside the class, for example `Snapshot* SnapshotTest::snapshot_ = nullptr;`. 3. Define `static void SetUpTestSuite()` to build the resource and `static void TearDownTestSuite()` to release it. The spelling matters: `SetupTestSuite` with a lower-case u compiles and is silently never called, and `override` cannot catch it because the function is `static`. GoogleTest calls `SetUpTestSuite()` before constructing the first fixture of the suite and `TearDownTestSuite()` after destroying the last. The docs note that a value-parameterized fixture may need these hooks to be `public`. ## What goes wrong with shared state **Order dependence.** The docs say test order is undefined, and the tools make that real: `--gtest_filter` runs a subset, `--gtest_shuffle` randomises order, and sharding splits tests across machines. If `PutOverwrites` changes the shared snapshot and `ReadsUser` expects the original, `ReadsUser` passes or fails depending on what ran first. The rule is strict: tests must either not modify the shared resource or restore it before the next test runs. **Repeated set-up with derived fixtures.** A static member function is inherited. If `ShardedSnapshotTest` derives from `SnapshotTest`, the derived suite calls the inherited `SetUpTestSuite()` again before its own first test. Code that allocates unconditionally leaks the first allocation unless `TearDownTestSuite()` freed it, so either release in `TearDownTestSuite()` and reset the pointer, or guard with `if (snapshot_ == nullptr)`. **Failure handling.** If `SetUpTestSuite()` records any failure, GoogleTest 1.18 marks every test in that suite as skipped rather than running it, still calls `TearDownTestSuite()`, and prints the suite under `SetUpTestSuite or TearDownTestSuite` as a failed test suite, with a nonzero exit status. `TearDownTestSuite()` must therefore cope with a resource that was never created. **Hidden coupling between helpers.** A test that caches a pointer or reference into the shared resource and a later test that rebuilds it leave a dangling handle. Keep the resource immutable after set-up wherever possible. ## Deciding whether it is worth it - Measure first. A temporary directory or a small in-memory map is cheap enough for per-test `SetUp()`. - Prefer sharing **immutable** data: a seeded snapshot opened read-only, a parsed schema, a compiled lookup table. - When tests need to write, give each one a **copy** made in `SetUp()` from the shared original, which keeps both speed and isolation. - For something every suite needs, such as a test server started once per run, use a `testing::Environment` registered in your own `main()` before `RUN_ALL_TESTS()`. With `gtest_main` the registration has to happen during static initialisation, which the docs advise against. ## A review checklist for suite-level state - Is the resource genuinely expensive, measured rather than assumed? - Is it immutable after `SetUpTestSuite()`, or does every writer restore it? - Is the allocation guarded or released, so a derived fixture's repeated call does not leak? - Does `TearDownTestSuite()` tolerate a set-up that failed part-way? - Are the hooks spelled `SetUpTestSuite` and `TearDownTestSuite` exactly, since no compiler check catches a typo in a static function? ## A worked check Running the suite with `--gtest_shuffle --gtest_repeat` a few times is a cheap way to flush out order dependence in shared state: a test that only passes in file order is likely to fail within a few iterations. The flags themselves are covered with the test runner material.

  • Why can SetUpTestSuite run more than once for what looks like one fixture?
    Because a derived fixture class forms its own test suite and inherits the static `SetUpTestSuite()`, so GoogleTest calls it again before that suite's first test. Allocation inside it must be guarded or paired with a release in `TearDownTestSuite()`, or the earlier resource leaks.
  • How do you share an expensive resource and still let tests write to it?
    Build the expensive original once in `SetUpTestSuite()` and treat it as read-only, then give each test a private copy in `SetUp()`, for example by copying a seeded snapshot directory into the test's own temporary directory. Tests stay independent while the expensive seeding happens once.

  • SetUpTestSuite() is guaranteed to run exactly once per fixture class.
  • Tests in one suite always run in the order they appear in the file.
  • A failure in SetUpTestSuite() lets the tests run and fail individually.
  • Spelling it SetupTestSuite still works because GoogleTest matches names loosely.
  • Suite-level set-up is the default choice because it makes suites faster.

Assumes GoogleTest 1.18, where a failure in SetUpTestSuite skips the suite's tests and is reported as a failed test suite.