In GoogleTest, how does TEST_F differ from TEST, and does each TEST_F get its own fixture object?
answer
- the first argument names a class
- members visible in the body
- construct, SetUp, body, TearDown, destroy
- no member state carries over
basics
~20 sTEST_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#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
Recall that TEST_F names a fixture class derived from testing::Test and that every test gets a fresh fixture object.
Walk through the construct, SetUp, body, TearDown, destroy sequence, including what happens after a fatal failure in SetUp.
Explain how per-test fixtures keep tests order-independent, and spot fixtures that hide expensive or unrelated set-up.
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.