skip to content

In a GoogleTest fixture, when should set-up and clean-up go in SetUp and TearDown rather than the constructor and destructor?

level: middleimportance: should knowfreq 50%

answer

  1. const members need a constructor
  2. fatal assertions need a void function
  3. virtual calls during construction
  4. a destructor must not throw

basics

~10 s

Prefer the constructor and destructor for plain initialisation, which allows const members and guaranteed base-first order. Use SetUp for set-up that needs ASSERT_* or calls virtual functions, and TearDown for clean-up that may throw.

solid answer

~40 s

GoogleTest's FAQ prefers the **constructor and destructor**: a member initialised in the constructor can be `const`, and a derived fixture's constructor always runs the base constructor first, whereas a derived `SetUp()` can forget to call the base one. Use **`SetUp()`** when set-up can fail and should stop the test, because fatal assertions such as `ASSERT_TRUE` do not compile in a constructor, and when set-up must call a virtual function a derived fixture overrides, since a call made during construction does not dispatch to the derived class. Use **`TearDown()`** when clean-up may throw, such as `std::filesystem::remove_all`, because destructors are implicitly non-throwing and an exception escaping one calls `std::terminate`. Declare both with `override`: `testing::Test` traps the misspelling `Setup()`, but `Teardown()` or `SetupTestSuite()` would silently never run.

code

cpp · 24 lines
cpp
#include <gtest/gtest.h>
#include <filesystem>
#include <string>

namespace fs = std::filesystem;

class KvStoreTest : public testing::Test {
 protected:
  // Constructor: plain initialisation, so the member can be const.
  KvStoreTest() : root_(fs::temp_directory_path() / "kv-store-test") {}

  // SetUp: work that can fail, so it may use fatal assertions.
  void SetUp() override {
    fs::create_directories(root_);
    ASSERT_TRUE(fs::is_directory(root_)) << "cannot create " << root_;
  }

  // TearDown: clean-up that may throw (remove_all can throw filesystem_error).
  void TearDown() override { fs::remove_all(root_); }

  const fs::path root_;
};

TEST_F(KvStoreTest, RootExists) { EXPECT_TRUE(fs::exists(root_)); }

go deeper

for a junior

Recall that SetUp and TearDown run around each test and that SetUp is spelled with a capital U.

for a middle

Explain the FAQ's rule: constructor by default for const members and ordering, SetUp for fatal assertions and virtual calls, TearDown for throwing clean-up.

for a senior

Spot set-up that silently never runs, partial set-up that breaks TearDown, and fixture hierarchies whose SetUp overrides skip the base.

for a principal

Define a fixture convention for the team, including override on every hook and where fallible set-up lives, so these traps are caught at compile time.

## Two places for per-test set-up A GoogleTest fixture is a class derived from `testing::Test`. For every `TEST_F`, the framework constructs a new fixture, calls `SetUp()`, runs the body, calls `TearDown()` and destroys the fixture. Per-test set-up can therefore live in either of two places, and so can clean-up: | Hook | Runs | Can use `ASSERT_*` | Can throw safely | Virtual dispatch to derived fixture | |---|---|---|---|---| | constructor | first | no | it can, and the framework reports it | no | | `SetUp()` | after construction | yes | yes, reported as a failure | yes | | `TearDown()` | after the body | yes | yes, reported as a failure | yes | | destructor | last | no | no: `std::terminate` | no | ## Why the constructor is the default The GoogleTest FAQ prefers the constructor and destructor, for two reasons: - **`const` members.** A member initialised in the constructor's member initialiser list can be declared `const`, such as the store's root path, so no test can change it by accident. - **Ordering in fixture hierarchies.** When `ShardedKvStoreTest` derives from `KvStoreTest`, C++ guarantees the base constructor runs before the derived one and the base destructor after it. With `SetUp()`, the derived override must remember to call `KvStoreTest::SetUp()` itself, at the right moment. ## When SetUp() is required 1. **Set-up that can fail and must stop the test.** Fatal assertions such as `ASSERT_TRUE` expand to a `return` statement with a `void` operand, which a constructor rejects at compile time; clang says the constructor "must not return void expression". In `SetUp()`, `ASSERT_TRUE(fs::is_directory(root_))` works, and a fatal failure there makes GoogleTest skip the test body. The alternative in a constructor is calling `std::abort()`, which ends the whole test program. 2. **Set-up that calls a virtual function a derived fixture overrides.** During construction the object's dynamic type is the class whose constructor is running, so a virtual call made from the base constructor runs the base version. By the time `SetUp()` runs, construction is complete, and the call dispatches to the derived override. ## When TearDown() is required Since C++11 a destructor without a `noexcept` specification gets the same exception specification as an implicitly declared one, which is non-throwing unless a base or member destructor may throw. An exception escaping such a destructor calls `std::terminate`, ending the test program. Clean-up that can throw, such as `std::filesystem::remove_all` reporting a `filesystem_error`, belongs in `TearDown()`, where GoogleTest catches an exception and reports it as a test failure. The FAQ also advises against GoogleTest assertions in a destructor, since a future version could make them throw. ## The misspelling trap `SetUp` has a capital U, and the framework's own documentation calls `Setup()` a common mistake. GoogleTest 1.18 defends that one spelling: `testing::Test` declares a private virtual `Setup()` returning `Setup_should_be_spelled_SetUp*`, so a fixture's `void Setup()` fails to compile with a different-return-type error, even without `override`. Other misspellings get no such trap: - `void Teardown()` compiles and is simply never called. - `static void SetupTestSuite()` compiles and is never called, and `override` cannot help because the function is `static`. Writing `override` on `SetUp()` and `TearDown()` turns any other spelling mistake into a compile error, which is why the primer recommends it. ## Skipping instead of failing Some set-up discovers that a test cannot meaningfully run, for example a storage backend that is not available on this machine. Calling `GTEST_SKIP() << "no backend";` in `SetUp()` marks the test as skipped rather than failed: GoogleTest checks for a skip after `SetUp()` returns and does not run the body, then calls `TearDown()` as usual. Use it only for genuine environmental gaps; a skip that hides a broken set-up is a silent coverage loss that reports look green on. ## A practical split - Initialise simple, infallible members in the constructor, and mark them `const` where possible. - Create files, directories, connections and anything you want to assert on in `SetUp()`. - Release resources whose release cannot throw in the destructor or in member types with their own destructors, such as `std::unique_ptr`. - Put throwing or assertion-bearing clean-up in `TearDown()`, and make it tolerate a `SetUp()` that stopped part-way, because `TearDown()` runs even after a fatal failure in `SetUp()`.

  • What happens to the test when SetUp() records a fatal failure?
    GoogleTest skips the test body, still calls `TearDown()`, then destroys the fixture, and the test is reported as failed. That is why `TearDown()` must handle partial set-up, for example by checking whether a directory exists before removing it.
  • Why does a derived fixture's SetUp() usually call the base SetUp() first?
    `SetUp()` is an ordinary virtual function, so overriding it replaces the base version instead of running both. Calling `KvStoreTest::SetUp()` at the start of the derived override restores the base-first order a constructor would have guaranteed automatically. Forgetting it is the classic bug the FAQ warns about.

  • ASSERT_* works in a fixture constructor as long as the fixture derives from testing::Test.
  • A virtual call from the fixture's constructor reaches the derived fixture's override.
  • Throwing from a fixture destructor is reported as an ordinary test failure.
  • Writing Teardown() instead of TearDown() always produces a compile error.
  • SetUp() is always preferable to the constructor because it runs later.

Assumes GoogleTest 1.18 for the Setup_should_be_spelled_SetUp trap and the misspellings it does not catch.