C++
Test fixtures
Learn shared setup with test fixtures.
What is a test fixture?
When several tests share the same setup code you define a test fixture instead of repeating it. A fixture derives from ::testing::Test and has SetUp() / TearDown() methods. Before each test SetUp runs, after it TearDown runs.
Tests using a fixture are written with TEST_F(FixtureName, TestName) instead of TEST. Example: class CalcTest : public ::testing::Test { protected: void SetUp() override { calc = new Calculator(); } Calculator* calc; };. Then TEST_F(CalcTest, Starts) { ... }. This ensures each test starts with a clean setup.
SetUp and TearDown lifecycle
In a fixture class SetUp() runs before each test and TearDown() runs after each test. In SetUp you prepare resources (objects, files, connections); in TearDown you clean them up. This keeps tests independent.
Example: void SetUp() override { list.clear(); list.push_back(1); }. Each test starts with {1}. void TearDown() override { list.clear(); } empties the list after the test. Members are protected: so tests can reach them. This ensures each test runs from the same starting state.
Exercise Write a CalcTest fixture
Derive a CalcTest fixture from ::testing::Test. Under protected: define void SetUp() override that sets int value = 42;; have an int value; member. Inside TEST_F(CalcTest, HasValue) call EXPECT_EQ(value, 42). In main print std::cout << "test: ready";.
Show example solution
#include <iostream>
#include <gtest/gtest.h>
class CalcTest : public ::testing::Test {
protected:
void SetUp() override {
value = 42;
}
int value;
};
TEST_F(CalcTest, HasValue) {
EXPECT_EQ(value, 42);
}
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}
Test yourself
-
When do you use TEST_F instead of TEST?
- To run the test faster
- When writing a single test
- To color the output
- When tests share setup code
Show answer
When tests share setup code — TEST_F is used with fixture classes that hold shared setup.
-
Match each piece to its role
- class CalcTest : public ::testing::Test
- Fixture class
- void SetUp() override
- Runs before each test
- void TearDown() override
- Runs after each test
- TEST_F(CalcTest, Name)
- Test with fixture
-
Complete the SetUp method
void ____() override {
value = 42;
}
Show answer
void SetUp() override {
value = 42;
}
Next lesson: Mock