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 repeating greeter:: prefixes or using declarations (analogous to declaring package greeter at the top of greeter_test.go in Go).
  • Inner namespace { ... } (Per-File Internal Linkage): Gives helper functions, fake implementations, and the C++ classes generated by TEST macros Internal Linkage within the current translation unit (.cc), preventing One Definition Rule (ODR) violations and linker symbol collisions across multiple *_test.cc files linked into the same test binary.

2. Pitfall: Never Name a Nested Namespace testing (Name Hiding)#

  • GoogleTest itself lives in the top-level ::testing namespace (eg. ::testing::Test, ::testing::ElementsAre).
  • Defining namespace greeter::testing causes C++ unqualified name lookup to stop at the inner greeter::testing scope rather than reaching ::testing (Name Hiding), breaking references such as testing::Test with 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:

  1. Synthesizing the C++ Class Name: Concatenates the two arguments with an underscore (_) to form <TestSuiteName>_<TestName>_Test.
  2. Grouping Test Reports: Formats console output and XML test results as QuizScorerTest.ScoresValidSubmission.
  3. CLI Test Filtering: Matches patterns passed to --gtest_filter when 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) and TEST(Foo, Bar_Baz)) to generate the exact same class Foo_Bar_Baz_Test and collide at compile or link time (GoogleTest FAQ). Use PascalCase without underscores for both arguments.
  • Use Descriptive TestName Identifiers: Replace vague names like Basic or Works with 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): Requires class FixtureClassName : public ::testing::Test to be defined beforehand. Because the generated test class inherits from FixtureClassName, protected: data members and helper methods on the fixture are directly accessible inside TestBody().
// 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 UserStoreTest object across TEST_F cases. To guarantee hermetic isolation so mutations in one test never pollute another, GoogleTest constructs and destroys a brand-new fixture instance for every single TEST_F:
    1. Construct a fresh UserStoreTest instance (constructor runs)
    2. Call SetUp()
    3. Run the TEST_F body ("alice" inserted in InsertsNewUser does not carry over to the next test)
    4. Call TearDown() (guaranteed to run even if the test body aborted early via ASSERT_*)
    5. Destroy the UserStoreTest instance (destructor runs)
  • 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 requires ASSERT_* macros: ASSERT_* expands to a return; statement on failure, which is legal inside void SetUp() but fails to compile inside a C++ constructor (and similarly when virtual dispatch is needed during setup).
  • Avoid Unnecessary Fixtures: Introducing a TEST_F fixture 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 for TEST_F only when multiple tests genuinely share setup state; otherwise, prefer plain TEST cases 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)
DimensionC++ GoogleTest (TEST_F)Go Standard testing (*testing.T)
Shared SetupImplicit Fixture constructor + void SetUp() overrideExplicit helper call inside test body (db := setupDB(ctx, t))
Fatal Setup FailureCannot use ASSERT_* in constructor -> use ASSERT_* (return;) inside SetUp()Call t.Fatalf(...) (runtime.Goexit()) directly inside the setup helper
Teardown MechanismTearDown() followed by automatic member destructors in reverse declaration order (RAII)Automatic t.Context() cancellation followed by t.Cleanup() callbacks in LIFO order
Early-Abort SafetyTearDown() and destructors still run after early return; from ASSERT_*Registered t.Cleanup() callbacks still run after t.Fatalf (Goexit)
Context State in TeardownMember objects remain intact until destructiont.Context() is already canceled before t.Cleanup() runs; DB/RPC teardown needs context.WithoutCancel(t.Context())
Once-per-Suite Setupstatic void SetUpTestSuite() / TearDownTestSuite()func TestMain(m *testing.M) (wrapping m.Run())
  • Why Both Tear Down in Reverse (LIFO) Order: In C++ UserStoreTest, declaring db_ before store_ (which holds &db_) constructs db_ -> store_ and destroys them in reverse order (~store_() -> ~db_()), preventing dangling references during teardown. Because Go has no destructors, registering t.Cleanup callbacks 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 FamilyDefining HeaderAllowed ScopeBehavior on FailurePrimary Purpose
CHECK* (CHECK, CHECK_EQ, CHECK_OK)"absl/log/check.h"Production & all codeLogs a stack trace and aborts the entire process immediatelyEnforcing invariants in production code where continuing is unsafe
ASSERT_* (ASSERT_EQ, ASSERT_NE, ASSERT_THAT)<gtest/gtest.h> / <gmock/gmock.h>Test code onlyRecords 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 onlyRecords a test failure and continues executing the rest of the current testStandard verification of behavior under test (default choice, analogous to Go t.Errorf)
  • Why CHECK Should Not Verify Test Outcomes: Using CHECK_OK(scorer.Score(...)) or CHECK_EQ(...) to assert behavior under test crashes the entire test binary when a check fails, preventing every remaining TEST case in the binary from running. Reserve CHECK in test files strictly for internal invariants of test helper utilities themselves.
  • When to Use ASSERT_* (and Its void Constraint): Default to EXPECT_* so a single run surfaces all failures in a test. Upgrade to ASSERT_* only when continuing the current function would crash or be nonsensical—for example, ASSERT_NE(user_ptr, nullptr); before user_ptr->name(), or ASSERT_EQ(items.size(), 1); before items[0]. Because ASSERT_* expands to return;, it can only be used inside functions returning void.

2. Common Matchers & Deterministic Testing Tips#

  1. String Comparisons (EXPECT_EQ vs. EXPECT_STREQ):
    • Whenever at least one side is std::string or absl::string_view, overloaded operator== compares string contents properly—use EXPECT_EQ(actual_str, "Hello").
    • Reserve EXPECT_STREQ(a, b) strictly for comparing two raw C string pointers (const char*), where EXPECT_EQ would compare pointer addresses instead of character contents.
  2. Verifying absl::Status and absl::StatusOr<T>:
    • Instead of CHECK_OK, use the gMock status matchers (IsOk(), IsOkAndHolds(), StatusIs()) from "absl/status/status_matchers.h".
#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
  1. 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::Notification or explicit completion callbacks to synchronize asynchronous work deterministically.