skip to content

Fixtures and Value Parameters

A fixture class gives each TEST_F fresh state through SetUp and TearDown, and TEST_P runs one body over many values. Interviewers ask how state is shared across a suite.

on this pageshow

explore

questions

5

In GoogleTest, how does TEST_F differ from TEST, and does each TEST_F get its own fixture object?

level: juniorimportance: must knowfreq 70%

answer

  1. the first argument names a class
  2. members visible in the body
  3. construct, SetUp, body, TearDown, destroy
  4. no member state carries over

basics

~20 s

TEST_F's first argument is a fixture class derived from testing::Test, and the test body can use its members. GoogleTest builds a fresh fixture object for every TEST_F and destroys it afterwards, so nothing stored in its members carries over.

solid answer

~40 s

`TEST(Suite, Name)` defines a free-standing test; `TEST_F(Fixture, Name)` names a **fixture class** derived from `testing::Test`, and that class name is also the suite name. The macro generates a class derived from the fixture, so the body can use its `protected` members and helpers directly. For **every** `TEST_F`, GoogleTest constructs a **new** fixture object, calls `SetUp()`, runs the body, calls `TearDown()` and destroys the object, deleting one fixture before it creates the next. Nothing one test writes into a non-static member is visible to the next; only `static` members and state outside the fixture persist. That makes each test independent of the order tests run in, and it is why expensive shared state needs the suite-level `SetUpTestSuite()` instead of a member.

code

cpp · 36 lines
cpp
#include <gtest/gtest.h>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <string>

namespace fs = std::filesystem;

class KvStoreTest : public testing::Test {
 protected:
  KvStoreTest() { std::puts("constructor"); }
  ~KvStoreTest() override { std::puts("destructor"); }
  void SetUp() override {
    dir_ = fs::temp_directory_path() /
           testing::UnitTest::GetInstance()->current_test_info()->name();
    fs::create_directories(dir_);
    std::puts("SetUp");
  }
  void TearDown() override {
    fs::remove_all(dir_);
    std::puts("TearDown");
  }
  void Put(const std::string& key, const std::string& value) {
    std::ofstream(dir_ / key) << value;
  }
  fs::path dir_;
};

TEST_F(KvStoreTest, PutCreatesFile) {
  Put("user", "ada");
  EXPECT_TRUE(fs::exists(dir_ / "user"));
}

TEST_F(KvStoreTest, StartsEmpty) {  // fresh object: no file from the test above
  EXPECT_TRUE(fs::is_empty(dir_));
}

go deeper

for a junior

Recall that TEST_F names a fixture class derived from testing::Test and that every test gets a fresh fixture object.

for a middle

Walk through the construct, SetUp, body, TearDown, destroy sequence, including what happens after a fatal failure in SetUp.

for a senior

Explain how per-test fixtures keep tests order-independent, and spot fixtures that hide expensive or unrelated set-up.

for a principal

Set conventions for fixture scope and shared helpers so suites stay fast, isolated and readable as they grow.

## Two ways to define a test GoogleTest, the C++ testing framework, offers two macros for an ordinary test: | Macro | First argument | Shared code | |---|---|---| | `TEST(SuiteName, TestName)` | any name for the test suite | none; each body stands alone | | `TEST_F(FixtureName, TestName)` | the name of a **fixture class** | the fixture's members and helper functions | The `_F` stands for fixture. A **test fixture** is a class derived from `testing::Test` that holds the objects and helper functions several tests need, such as a temporary directory and a key-value store opened inside it. Both arguments must be valid C++ identifiers without underscores, and the fixture class must be defined before the first `TEST_F` that names it. ## What the macro generates `TEST_F(KvStoreTest, PutCreatesFile)` expands to a class derived from `KvStoreTest` whose `TestBody()` member function holds your test body. Because the body is a member function of a derived class: - it can use the fixture's `protected` and `public` members, such as `dir_` and `Put(...)`, without qualification; - it cannot use `private` members, which is why fixtures conventionally declare their state `protected`; - the fixture must be default-constructible, since the framework creates it. The suite name in the output is the fixture class name, so all tests of one fixture appear together. All tests in one suite must use the same fixture class: a `TEST` and a `TEST_F` sharing a suite name compile, but at run time GoogleTest fails the odd one out with "mixing TEST_F and TEST in the same test suite is illegal". ## One fresh object per test For each `TEST_F`, GoogleTest performs the same sequence: 1. Construct a new fixture object. 2. Call `SetUp()`. 3. Run the test body, unless `SetUp()` produced a fatal failure or skipped the test. 4. Call `TearDown()`, which runs even when `SetUp()` or the body failed. 5. Destroy the fixture object. GoogleTest **always deletes one fixture before creating the next** and **never reuses** a fixture object for a second test. In the key-value store example, the first test writes a file into its own directory, and the second test finds an empty directory because it has a new fixture with a new `SetUp()`. ## Why per-test objects matter - **Independence.** A test cannot pass only because an earlier test left data in the fixture's members, so tests can run alone, filtered or in shuffled order and still mean the same thing. - **Debuggability.** A failing test can be re-run on its own and reproduces, because its starting state comes only from the fixture's set-up code. - **Cost.** Re-running set-up for every test is the price. When a resource is expensive and read-only, GoogleTest offers suite-level hooks, `static void SetUpTestSuite()` and `static void TearDownTestSuite()`, which run once around the whole suite. ## Fixtures built on fixtures A fixture can derive from another fixture, which is how a family of related suites shares set-up without copying it: - `class ShardedKvStoreTest : public KvStoreTest { ... };` reuses the base directory handling and adds its own members. - Tests written with `TEST_F(ShardedKvStoreTest, ...)` form a separate suite named after the derived class, and each still gets its own fresh object. - The base constructor runs before the derived one automatically; an overriding `SetUp()` must call `KvStoreTest::SetUp()` itself if it wants the base set-up. Keep such hierarchies shallow. Two levels are common; a deeper chain makes it hard to see what state a test starts from. ## Choosing TEST or TEST_F - Use `TEST` when the body needs nothing beyond local variables; a fixture adds indirection for no gain. - Use `TEST_F` when two or more tests need the same set-up or helpers. Duplicated set-up code in several `TEST` bodies is the usual sign. - Keep fixture members to what most tests use. A fixture that sets up ten objects for tests that each touch one makes every failure harder to read. ## Common mistakes - Expecting a member changed in one test to be seen by the next; every test gets a new object. - Making fixture members `private`, which the generated subclass cannot access. - Naming a suite in `TEST` the same as an existing fixture class, which mixes two kinds of test in one suite and fails at run time. - Putting expensive per-run work, such as loading a large data file, in the constructor or `SetUp()` and then wondering why the suite is slow.

  • Does TearDown() run when SetUp() hits a fatal failure?
    Yes. If `SetUp()` produces a fatal failure or calls `GTEST_SKIP()`, GoogleTest skips the test body but still calls `TearDown()` and then destroys the fixture, so clean-up code must cope with set-up that stopped part-way, for example a directory that was never created.
  • Can two tests share data through a fixture member if they always run in file order?
    No. Each `TEST_F` gets a new fixture object, so a member written in one test is gone before the next starts. Sharing needs a `static` member set up in `SetUpTestSuite()`, and even then tests must not depend on order, since filters and shuffling change it.

A hotel room cleaned between guests: each guest (test) gets the same furnishings (fixture), set up fresh on arrival and cleared on departure, and nothing the previous guest left behind is still there.

  • All tests of a TEST_F suite share one fixture object for speed.
  • TEST_F's first argument is just a suite label like TEST's.
  • Fixture members should be private to keep tests from changing them.
  • TearDown() is skipped when the test body fails.
  • A test can rely on state left by the test defined above it.
open as a page

In GoogleTest, how do TEST_P and INSTANTIATE_TEST_SUITE_P run one test body over many values, and how are the generated tests named?

level: middleimportance: must knowfreq 55%

basics

~20 s

A fixture derived from testing::TestWithParam<T> holds the TEST_P bodies, which read GetParam(). INSTANTIATE_TEST_SUITE_P supplies values from a generator such as Values or Combine, and each value becomes a test named Prefix/Suite.Test/index unless a name generator supplies the suffix.

open as a page

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%

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.

open as a page

In GoogleTest, how do typed tests differ from type-parameterized tests, and why must a typed test body use this-> for fixture members?

level: middleimportance: should knowfreq 35%

basics

~20 s

Typed tests fix the type list where the suite is written with TYPED_TEST_SUITE; type-parameterized tests define patterns first and are instantiated later, possibly elsewhere. The body is a member of a class template derived from the fixture, so its members need this->.

open as a page

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%

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.

open as a page