Test fixtures
- C++ course
- Advanced
- Lesson 40/83
- 5 min
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.
Practice 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";.
Starter code
#include <iostream>
#include <gtest/gtest.h>
// Define the CalcTest fixture class
// Add a TEST_F macro for CalcTest
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}Sample 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;
}Expected output
test: ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: TEST_F is used with fixture classes that hold shared setup.
2 Match each piece to its role
| Term | Meaning |
|---|---|
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 |
3 Complete the SetUp method
void ____() override {
value = 42;
}
void SetUp() override {
value = 42;
}
Explanation: The SetUp method sets the value before each test.