Unit Testing#
Practical guidelines for C++ unit testing with open-source GoogleTest (google/googletest) and Abseil (abseil-cpp), covering test file namespace layout, how TEST and TEST_F expand under the hood, Test Fixture lifecycles, and choosing between CHECK, ASSERT_*, and EXPECT_*.
1. Namespace Structure in Test Files#
1. Idiomatic Layout: namespace <pkg> { namespace { ... } }#
When greeter.h and greeter.cc declare symbols inside namespace greeter, the corresponding greeter_test.cc should open the same outer namespace greeter and wrap the test definitions inside an inner anonymous namespace (namespace { ... }).
// greeter_test.cc
#include "greeter/greeter.h"
#include <string>
#include <gtest/gtest.h>
#include "absl/strings/str_cat.h"
namespace greeter {
namespace {
TEST(GreeterTest, FormatsGreetingWithUserName) {
Greeter greeter; // Accessible directly without greeter:: qualification
std::string name = "Alice";
EXPECT_EQ(greeter.SayHello(name), absl::StrCat("Hello, ", name));
}
} // namespace
} // namespace greeter
- Outer
namespace greeter(Unqualified SUT Access): Allows tests to reference classes, functions, and constants in the package under test directly without repeatinggreeter::prefixes orusingdeclarations (analogous to declaringpackage greeterat the top ofgreeter_test.goin Go). - Inner
namespace { ... }(Per-File Internal Linkage): Gives helper functions, fake implementations, and the C++ classes generated byTESTmacros Internal Linkage within the current translation unit (.cc), preventing One Definition Rule (ODR) violations and linker symbol collisions across multiple*_test.ccfiles linked into the same test binary.
2. Pitfall: Never Name a Nested Namespace testing (Name Hiding)#
- GoogleTest itself lives in the top-level
::testingnamespace (eg.::testing::Test,::testing::ElementsAre). - Defining
namespace greeter::testingcauses C++ unqualified name lookup to stop at the innergreeter::testingscope rather than reaching::testing(Name Hiding), breaking references such astesting::Testwith compiler errors.
2. How the TEST Macro Expands & Naming Rules#
1. What TEST(TestSuiteName, TestName) Actually Generates#
Although TEST(QuizScorerTest, ScoresValidSubmission) looks like a function definition, the preprocessor actually defines a unique C++ subclass of ::testing::Test on the spot and registers it automatically during static initialization (gtest/internal/gtest-internal.h).
// What you write
TEST(QuizScorerTest, ScoresValidSubmission) {
QuizScorer scorer;
EXPECT_EQ(scorer.Score("A"), 100);
}
// Simplified C++ code generated by the preprocessor
class QuizScorerTest_ScoresValidSubmission_Test : public ::testing::Test {
private:
void TestBody() override;
static ::testing::TestInfo* const test_info_; // Auto-registers before main()
};
void QuizScorerTest_ScoresValidSubmission_Test::TestBody() {
QuizScorer scorer;
EXPECT_EQ(scorer.Score("A"), 100);
}2. How TestSuiteName and TestName Are Used & Naming Rules#
In a standalone TEST(...), neither QuizScorerTest nor ScoresValidSubmission is a pre-existing type or variable; both identifiers are coined right at the macro invocation (by convention, TestSuiteName appends Test to the class or module under test, such as QuizScorerTest).
GoogleTest uses these two names in three places:
- Synthesizing the C++ Class Name: Concatenates the two arguments with an underscore (
_) to form<TestSuiteName>_<TestName>_Test. - Grouping Test Reports: Formats console output and XML test results as
QuizScorerTest.ScoresValidSubmission. - CLI Test Filtering: Matches patterns passed to
--gtest_filterwhen running a subset of tests.
$ ./quiz_scorer_test --gtest_filter="QuizScorerTest.*"- Avoid Underscores (
_) in Both Names: Because the macro joins the two tokens with_, putting underscores inside either name can cause two distinct tests (eg.TEST(Foo_Bar, Baz)andTEST(Foo, Bar_Baz)) to generate the exact sameclass Foo_Bar_Baz_Testand collide at compile or link time (GoogleTest FAQ). UsePascalCasewithout underscores for both arguments. - Use Descriptive
TestNameIdentifiers: Replace vague names likeBasicorWorkswith behavior-describing names (eg.ScoresValidSubmission,RejectsEmptyAnswer) so failure logs immediately communicate what broke.
3. Test Fixtures (TEST_F) & Lifecycle#
1. TEST vs. TEST_F Side-by-Side#
A Test Fixture is a reusable base class that bundles shared objects (eg. fake databases, temporary directories) and common setup/cleanup logic across multiple test cases.
TEST(SuiteName, TestName): Requires no prior class definition; the generated test class inherits directly from::testing::Test.TEST_F(FixtureClassName, TestName)(F= Fixture): Requiresclass FixtureClassName : public ::testing::Testto be defined beforehand. Because the generated test class inherits fromFixtureClassName,protected:data members and helper methods on the fixture are directly accessible insideTestBody().
// 1. No shared setup needed: use plain TEST (no fixture class required)
TEST(GreeterTest, ReturnsFormattedHello) {
Greeter greeter;
EXPECT_EQ(greeter.SayHello("Bob"), "Hello, Bob");
}
// 2. Multiple tests share nontrivial setup: define a fixture class and use TEST_F
class UserStoreTest : public ::testing::Test {
protected:
void SetUp() override {
ASSERT_TRUE(db_.ConnectInMemory());
store_ = std::make_unique<UserStore>(&db_);
}
FakeDatabase db_;
std::unique_ptr<UserStore> store_;
};
// Expands to -> class UserStoreTest_InsertsNewUser_Test : public UserStoreTest
TEST_F(UserStoreTest, InsertsNewUser) {
EXPECT_TRUE(store_->Insert("alice"));
EXPECT_EQ(store_->Count(), 1);
}
// Expands to -> class UserStoreTest_ReturnsFalseOnDuplicate_Test : public UserStoreTest
TEST_F(UserStoreTest, ReturnsFalseOnDuplicate) {
ASSERT_TRUE(store_->Insert("alice"));
EXPECT_FALSE(store_->Insert("alice"));
}2. Instance Isolation & SetUp() / TearDown() Lifecycle#
- Fresh Fixture Instance per Test Case (No Shared State):
GoogleTest does not reuse the same
UserStoreTestobject acrossTEST_Fcases. To guarantee hermetic isolation so mutations in one test never pollute another, GoogleTest constructs and destroys a brand-new fixture instance for every singleTEST_F:- Construct a fresh
UserStoreTestinstance (constructor runs) - Call
SetUp() - Run the
TEST_Fbody ("alice"inserted inInsertsNewUserdoes not carry over to the next test) - Call
TearDown()(guaranteed to run even if the test body aborted early viaASSERT_*) - Destroy the
UserStoreTestinstance (destructor runs)
- Construct a fresh
- Constructor/Destructor vs.
SetUp()/TearDown():- Prefer constructors and destructors by default so members can be initialized in initializer lists, marked
const, and managed cleanly via RAII. - Override
void SetUp()when setup requiresASSERT_*macros:ASSERT_*expands to areturn;statement on failure, which is legal insidevoid SetUp()but fails to compile inside a C++ constructor (and similarly when virtual dispatch is needed during setup).
- Prefer constructors and destructors by default so members can be initialized in initializer lists, marked
- Avoid Unnecessary Fixtures: Introducing a
TEST_Ffixture just to hold a couple of local variables forces readers to jump back and forth between the fixture class at the top of the file and the test body below. Reach forTEST_Fonly when multiple tests genuinely share setup state; otherwise, prefer plainTESTcases with explicit local variables or helper functions.
3. Comparison with Go testing Lifecycle (t.Cleanup & t.Context)#
Whereas C++ GoogleTest automates setup and teardown implicitly through inheritance (Fixture class) and object lifetime (RAII), Go testing has no fixture inheritance or SetUp() / TearDown() hooks—instead achieving the exact same per-test isolation via explicit setup helpers and a LIFO t.Cleanup() callback stack.
[C++ GoogleTest (TEST_F)]
Constructor (members in order) ──▶ SetUp() ──▶ TestBody() ──▶ TearDown() ──▶ Destructor (members in reverse order)
[Go testing (t.Run)]
Init t.Context() ──▶ setupHelper(t) + register t.Cleanup() ──▶ Test body ──▶ Cancel t.Context() ──▶ Run t.Cleanup() (LIFO)| Dimension | C++ GoogleTest (TEST_F) | Go Standard testing (*testing.T) |
|---|---|---|
| Shared Setup | Implicit Fixture constructor + void SetUp() override | Explicit helper call inside test body (db := setupDB(ctx, t)) |
| Fatal Setup Failure | Cannot use ASSERT_* in constructor -> use ASSERT_* (return;) inside SetUp() | Call t.Fatalf(...) (runtime.Goexit()) directly inside the setup helper |
| Teardown Mechanism | TearDown() followed by automatic member destructors in reverse declaration order (RAII) | Automatic t.Context() cancellation followed by t.Cleanup() callbacks in LIFO order |
| Early-Abort Safety | TearDown() and destructors still run after early return; from ASSERT_* | Registered t.Cleanup() callbacks still run after t.Fatalf (Goexit) |
| Context State in Teardown | Member objects remain intact until destruction | t.Context() is already canceled before t.Cleanup() runs; DB/RPC teardown needs context.WithoutCancel(t.Context()) |
| Once-per-Suite Setup | static void SetUpTestSuite() / TearDownTestSuite() | func TestMain(m *testing.M) (wrapping m.Run()) |
- Why Both Tear Down in Reverse (LIFO) Order: In C++
UserStoreTest, declaringdb_beforestore_(which holds&db_) constructsdb_->store_and destroys them in reverse order (~store_()->~db_()), preventing dangling references during teardown. Because Go has no destructors, registeringt.Cleanupcallbacks as each resource is created and running them LIFO reproduces the exact same dependency-safe reverse destruction order as C++ RAII.
4. Verification Macros: CHECK vs. ASSERT_* vs. EXPECT_*#
1. Header Ownership & Failure Behavior#
Although all three are C preprocessor #define macros invoked without a testing:: namespace prefix, they belong to completely different libraries and behave very differently on failure (mirroring panic vs. t.Fatalf vs. t.Errorf in Go testing).
| Macro Family | Defining Header | Allowed Scope | Behavior on Failure | Primary Purpose |
|---|---|---|---|---|
CHECK* (CHECK, CHECK_EQ, CHECK_OK) | "absl/log/check.h" | Production & all code | Logs a stack trace and aborts the entire process immediately | Enforcing invariants in production code where continuing is unsafe |
ASSERT_* (ASSERT_EQ, ASSERT_NE, ASSERT_THAT) | <gtest/gtest.h> / <gmock/gmock.h> | Test code only | Records a test failure and executes return; from the current function (subsequent TEST cases still run) | Checking preconditions required for the rest of the test body to run safely (analogous to Go t.Fatalf) |
EXPECT_* (EXPECT_EQ, EXPECT_TRUE, EXPECT_THAT) | <gtest/gtest.h> / <gmock/gmock.h> | Test code only | Records a test failure and continues executing the rest of the current test | Standard verification of behavior under test (default choice, analogous to Go t.Errorf) |
- Why
CHECKShould Not Verify Test Outcomes: UsingCHECK_OK(scorer.Score(...))orCHECK_EQ(...)to assert behavior under test crashes the entire test binary when a check fails, preventing every remainingTESTcase in the binary from running. ReserveCHECKin test files strictly for internal invariants of test helper utilities themselves. - When to Use
ASSERT_*(and ItsvoidConstraint): Default toEXPECT_*so a single run surfaces all failures in a test. Upgrade toASSERT_*only when continuing the current function would crash or be nonsensical—for example,ASSERT_NE(user_ptr, nullptr);beforeuser_ptr->name(), orASSERT_EQ(items.size(), 1);beforeitems[0]. BecauseASSERT_*expands toreturn;, it can only be used inside functions returningvoid.
2. Common Matchers & Deterministic Testing Tips#
- String Comparisons (
EXPECT_EQvs.EXPECT_STREQ):- Whenever at least one side is
std::stringorabsl::string_view, overloadedoperator==compares string contents properly—useEXPECT_EQ(actual_str, "Hello"). - Reserve
EXPECT_STREQ(a, b)strictly for comparing two raw C string pointers (const char*), whereEXPECT_EQwould compare pointer addresses instead of character contents.
- Whenever at least one side is
- Verifying
absl::Statusandabsl::StatusOr<T>:- Instead of
CHECK_OK, use the gMock status matchers (IsOk(),IsOkAndHolds(),StatusIs()) from"absl/status/status_matchers.h".
- Instead of
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "absl/status/statusor.h"
namespace auth {
namespace {
using ::absl_testing::IsOk;
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::testing::HasSubstr;
TEST(TokenValidatorTest, ValidatesFormatAndExtractsUserId) {
TokenValidator validator;
// 1. Verify an OK absl::Status
EXPECT_THAT(validator.Ping(), IsOk());
// 2. Verify an OK absl::StatusOr<T> and its inner value in one assertion
absl::StatusOr<int> user_id = validator.ParseUserId("uid:42");
EXPECT_THAT(user_id, IsOkAndHolds(42));
// 3. Verify a specific error code and message substring
EXPECT_THAT(validator.ParseUserId(""),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty")));
}
} // namespace
} // namespace auth
- Never Sleep for Fixed Durations in Tests:
- Waiting with
absl::SleepFor(absl::Seconds(2))or fixed wall-clock timeouts makes tests slow and causes flaky failures under heavy CI load. - Inject a fake clock interface when testing time-dependent logic so tests can advance time instantaneously, and use concurrency primitives like
absl::Notificationor explicit completion callbacks to synchronize asynchronous work deterministically.
- Waiting with