Jesse A. Green / notebook

GoogleTest User Guide

Generated June 2026 from google/googletest at 7140cd4

AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it.

GoogleTest is Google's C++ testing and mocking framework. It bundles two closely related libraries that ship and release together:

  • GoogleTest (often called gtest) — an xUnit-style unit testing framework with a rich set of assertions, automatic test discovery, fixtures, parameterized tests, and death tests.
  • GoogleMock (often called gmock) — a library for creating and using C++ mock objects, integrated with GoogleTest's assertions and matchers.

This guide teaches you how to install GoogleTest, write your first tests, use every major feature, mock your dependencies, run and filter tests from the command line, and troubleshoot the most common problems. It is built entirely from the framework's own source and reference documentation.

Note

GoogleTest requires a C++ compiler supporting at least C++17. The main/1.17.x line targets C++17; the project follows Google's Foundational C++ Support Policy.


1. Quick Start

The fastest path to a green test. Create a project, declare a dependency on GoogleTest with CMake, write one test, and run it.

1. Create CMakeLists.txt:

cmake_minimum_required(VERSION 3.14)
project(my_project)

# GoogleTest requires at least C++17
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

enable_testing()

add_executable(hello_test hello_test.cc)
target_link_libraries(hello_test GTest::gtest_main)

include(GoogleTest)
gtest_discover_tests(hello_test)

2. Create hello_test.cc:

#include <gtest/gtest.h>

// Demonstrate some basic assertions.
TEST(HelloTest, BasicAssertions) {
  // Expect two strings not to be equal.
  EXPECT_STRNE("hello", "world");
  // Expect equality.
  EXPECT_EQ(7 * 6, 42);
}

3. Build and run:

cmake -S . -B build
cmake --build build
cd build && ctest

Expected output:

Test project .../my_project/build
    Start 1: HelloTest.BasicAssertions
1/1 Test #1: HelloTest.BasicAssertions ........   Passed    0.00 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.01 sec

Tip

Linking against GTest::gtest_main (instead of GTest::gtest) gives you a ready-made main() that initializes GoogleTest and runs every test. You almost never need to write your own main().


2. Installation & Setup

GoogleTest is consumed as a build-time dependency. Pick the method that matches your build system.

2.1 Requirements

Requirement Detail
C++ standard C++17 or newer (the 1.17.x line requires C++17)
Compiler Any compatible GCC, Clang, or MSVC (see the support matrix)
OS Linux, macOS, Windows (and more — POSIX, Cygwin, QNX, FreeBSD, OpenBSD)
Build tool CMake 3.14+ or Bazel 7.0+ (other systems supported via pkg-config)

Note

CMake support is community-maintained — the GoogleTest maintainers use Bazel internally. Both paths are fully supported for consumers; this only affects who fixes build-system bugs.

This is the method shown in the Quick Start. It downloads a pinned version of GoogleTest at configure time, so you don't need a system-wide install.

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/<commit-hash>.zip
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

Tip

Pin to a specific Git commit hash (as in the URL above) and update it deliberately. The maintainers recommend updating the hash often to track the latest version.

Then link your test target to one of the imported targets:

Target Use it when
GTest::gtest You provide your own main()
GTest::gtest_main You want GoogleTest's main() (most common)
GTest::gmock You use mocking and provide your own main()
GTest::gmock_main You use mocking and want a ready-made main()

2.3 Bazel

GoogleTest is the maintainers' first-class build path. As of Bazel 7.0, consume it through the Bazel Central Registry.

Create MODULE.bazel:

# Choose the most recent version available at
# https://registry.bazel.build/modules/googletest
bazel_dep(name = "googletest", version = "1.17.0")

Create a BUILD file with a cc_test rule:

cc_test(
    name = "hello_test",
    size = "small",
    srcs = ["hello_test.cc"],
    deps = [
        "@googletest//:gtest",
        "@googletest//:gtest_main",
    ],
)

Build and run:

bazel test --cxxopt=-std=c++17 --test_output=all //:hello_test

Expected output:

==================== Test output for //:hello_test:
Running main() from gmock_main.cc
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from HelloTest
[ RUN      ] HelloTest.BasicAssertions
[       OK ] HelloTest.BasicAssertions (0 ms)
[----------] 1 test from HelloTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.

Note

For MSVC, use --cxxopt=/std:c++17 instead of --cxxopt=-std=c++17.

2.4 Other build systems via pkg-config

GoogleTest ships pkg-config .pc files (gtest, gtest_main, gmock, gmock_main) that report the include path, required macros, and link flags.

find_package(PkgConfig)
pkg_search_module(GTEST REQUIRED gtest_main)

add_executable(testapp)
target_sources(testapp PRIVATE samples/sample3_unittest.cc)
target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS})
target_compile_options(testapp PRIVATE ${GTEST_CFLAGS})

enable_testing()
add_test(first_and_only_test testapp)

Important

Prefer ${GTEST_CFLAGS} over ${GTEST_INCLUDE_DIRS} and ${GTEST_LDFLAGS} over ${GTEST_LIBRARIES}. The _CFLAGS/_LDFLAGS variants carry the -pthread flag and threading macros that the include-dir/libraries variants silently drop — omitting them causes subtle link or runtime failures.

If pkg-config can't find GoogleTest after a manual install, point it at the install location:

export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig

2.5 Including the headers

You're writing Include
Tests only #include <gtest/gtest.h>
Tests with matchers (EXPECT_THAT) #include <gmock/gmock.h> (brings in matchers)
Mocks #include <gmock/gmock.h>
"Catching" framework failures #include <gtest/gtest-spi.h>

3. Writing Your First Tests

3.1 Core concepts

Before writing tests, learn the vocabulary — GoogleTest's terms differ subtly from other frameworks.

Term Meaning
Assertion A macro that checks a condition. Result is success, nonfatal failure, or fatal failure.
Test A function using assertions to verify behavior. Fails if any assertion fails or it crashes.
Test suite A group of related tests that can share data and subroutines.
Test fixture A class holding objects/subroutines shared across the tests in a suite.
Test program An executable containing one or more test suites.

Warning

Historically GoogleTest used Test Case for what it now calls a Test Suite. The preferred API is TestSuite; the older TestCase API is deprecated. When you read older code or messages, treat "test case" as "test suite".

3.2 The TEST() macro

Use TEST(TestSuiteName, TestName) to define a standalone test:

int Factorial(int n);  // Returns the factorial of n

// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
  EXPECT_EQ(Factorial(0), 1);
}

// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
  EXPECT_EQ(Factorial(1), 1);
  EXPECT_EQ(Factorial(2), 2);
  EXPECT_EQ(Factorial(3), 6);
  EXPECT_EQ(Factorial(8), 40320);
}

Tests with the same first argument belong to the same test suite. Tests register themselves automatically — you never list them anywhere.

Caution

Both TestSuiteName and TestName must be valid C++ identifiers and must not contain underscores (_). GoogleTest reserves _ for special prefixes like DISABLED_, and certain underscore placements produce invalid C++ that breaks on new compilers. See the FAQ for the full rationale.

3.3 ASSERT_* vs EXPECT_*

Every comparison macro comes in two flavors:

Family On failure Use when
EXPECT_* Nonfatal — reports the failure, test continues You want to see all failures in one run (preferred default)
ASSERT_* Fatal — reports the failure and returns from the current function Continuing makes no sense (e.g. a null pointer you're about to dereference)
ASSERT_NE(ptr, nullptr);   // If this fails, the function returns immediately,
EXPECT_EQ(*ptr, 42);       // so we never dereference a null ptr here.

Warning

Because a failed ASSERT_* returns immediately, it may skip cleanup code that follows it, potentially leaking resources. If you allocate before an ASSERT_*, prefer RAII or fixtures so cleanup still runs.

3.4 Custom failure messages

Stream extra context into any assertion with <<:

ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";

for (int i = 0; i < x.size(); ++i) {
  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}

Anything streamable to std::ostream (including C strings and std::string) can be streamed to an assertion. Wide strings are translated to UTF-8 when printed.

3.5 Running the tests

After defining tests, a main() that links gtest_main runs them all. If you need a custom main():

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

RUN_ALL_TESTS() runs every test in the link unit and returns 0 on success or 1 on any failure.

Important

You must return the value of RUN_ALL_TESTS() from main(), and you must call it only once. Ignoring the return value is a compiler error with GCC — the automated testing service uses the process exit code, not stdout, to decide pass/fail. Calling it more than once is unsupported.

Note

You must call testing::InitGoogleTest() before RUN_ALL_TESTS(), or command-line flags won't be parsed. On Windows it also accepts wide strings (UNICODE mode).


4. Test Fixtures: Sharing Setup Across Tests

When several tests operate on similar data, a fixture lets you reuse the same object configuration without copy-pasting setup.

To create a fixture:

  1. Derive a class from testing::Test, starting the body with protected:.
  2. Declare the objects your tests will use as members.
  3. Optionally write a constructor or SetUp() to initialize them before each test.
  4. Optionally write a destructor or TearDown() to release resources after each test.
template <typename E> class Queue { /* Enqueue, Dequeue, size ... */ };

class QueueTest : public testing::Test {
 protected:
  QueueTest() {
     // q0_ remains empty
     q1_.Enqueue(1);
     q2_.Enqueue(2);
     q2_.Enqueue(3);
  }

  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};

Write the tests with TEST_F() (the _F is for "Fixture"). The first argument is the fixture class name:

TEST_F(QueueTest, IsEmptyInitially) {
  EXPECT_EQ(q0_.size(), 0);
}

TEST_F(QueueTest, DequeueWorks) {
  int* n = q0_.Dequeue();
  EXPECT_EQ(n, nullptr);

  n = q1_.Dequeue();
  ASSERT_NE(n, nullptr);
  EXPECT_EQ(*n, 1);
  EXPECT_EQ(q1_.size(), 0);
  delete n;
}

For each TEST_F, GoogleTest creates a fresh fixture object, calls SetUp(), runs the body, calls TearDown(), and deletes the object. Tests never share a fixture instance, so one test's changes can't affect another.

Caution

A common mistake is spelling SetUp() as Setup() (lower-case u) — it then never runs. Add override so the compiler catches the typo: void SetUp() override { ... }.

4.1 Constructor/destructor vs. SetUp()/TearDown()

Use the constructor/destructor Use SetUp()/TearDown()
Default — lets you make members const; base class ctor/dtor always run in the right order You need to call a virtual method (not allowed in ctors/dtors)
Setup could cause a fatal assertion (ASSERT_* can't be used in ctors/dtors)
Teardown could throw an exception (throwing in a destructor is undefined behavior)

4.2 Deriving fixtures

You can share fixture logic by deriving one fixture from another. Remember to chain the base class's SetUp()/TearDown():

class FooTest : public BaseTest {
 protected:
  void SetUp() override {
    BaseTest::SetUp();   // base first
    // ... FooTest setup ...
  }
  void TearDown() override {
    // ... FooTest cleanup ...
    BaseTest::TearDown();  // base last
  }
};

If two suites only need the same base fixture with no extra logic, just alias it:

typedef BaseTest FooTest;
typedef BaseTest BarTest;

5. The Assertion Library

GoogleTest provides a broad assertion set. Every macro below has both an EXPECT_ and ASSERT_ form unless noted. Add #include <gtest/gtest.h>.

5.1 Boolean and explicit pass/fail

Macro Verifies
EXPECT_TRUE(c) c is true
EXPECT_FALSE(c) c is false
SUCCEED() Generates a success (documentary; does not by itself pass the test)
FAIL() Generates a fatal failure (void-returning functions only)
ADD_FAILURE() Generates a nonfatal failure
ADD_FAILURE_AT(file, line) Nonfatal failure attributed to a specific location

5.2 Binary comparison

Macro Verifies
EXPECT_EQ(a, b) a == b
EXPECT_NE(a, b) a != b
EXPECT_LT(a, b) a < b
EXPECT_LE(a, b) a <= b
EXPECT_GT(a, b) a > b
EXPECT_GE(a, b) a >= b

Warning

On pointers, EXPECT_EQ/EXPECT_NE do pointer equality. For C strings (const char*) they compare addresses, not contents — use the string macros below. When comparing a pointer to null, prefer EXPECT_EQ(ptr, nullptr) over EXPECT_EQ(ptr, NULL).

5.3 C-string comparison

These compare C strings by content (use EXPECT_EQ for std::string):

Macro Verifies
EXPECT_STREQ(s1, s2) Same contents
EXPECT_STRNE(s1, s2) Different contents
EXPECT_STRCASEEQ(s1, s2) Same contents, ignoring case
EXPECT_STRCASENE(s1, s2) Different contents, ignoring case

5.4 Floating-point comparison

Floating-point values rarely match exactly, so don't use EXPECT_EQ:

Macro Verifies
EXPECT_FLOAT_EQ(a, b) floats within 4 ULPs of each other
EXPECT_DOUBLE_EQ(a, b) doubles within 4 ULPs of each other
EXPECT_NEAR(a, b, abs_error) |a - b| <= abs_error

5.5 Exception assertions

Require exceptions enabled in the build:

Macro Verifies
EXPECT_THROW(stmt, type) stmt throws an exception of type
EXPECT_ANY_THROW(stmt) stmt throws any exception
EXPECT_NO_THROW(stmt) stmt throws nothing
EXPECT_NO_THROW({
  int n = 5;
  DoSomething(&n);
});

5.6 Predicate assertions (better messages)

When you need a complex boolean check but want the argument values printed on failure:

bool MutuallyPrime(int m, int n);
EXPECT_PRED2(MutuallyPrime, b, c);  // prints b and c on failure

EXPECT_PRED1 through EXPECT_PRED5 take a predicate plus 1–5 values. For full control of the failure message, use EXPECT_PRED_FORMAT1..5 with a predicate-formatter that returns testing::AssertionResult.

5.7 Matcher-based assertions: EXPECT_THAT

EXPECT_THAT(value, matcher) is the most expressive assertion — it reads like English and produces informative messages. Requires #include <gmock/gmock.h>.

using ::testing::AllOf;
using ::testing::Gt;
using ::testing::Lt;
using ::testing::MatchesRegex;
using ::testing::StartsWith;

EXPECT_THAT(value1, StartsWith("Hello"));
EXPECT_THAT(value2, MatchesRegex("Line \\d+"));
ASSERT_THAT(value3, AllOf(Gt(5), Lt(10)));

See §8 Matchers for the full catalog.

5.8 Other assertions

Macro / call Purpose
StaticAssertTypeEq<T1, T2>() Compile-time check that two types are identical
EXPECT_HRESULT_SUCCEEDED(expr) / EXPECT_HRESULT_FAILED(expr) Windows HRESULT success/failure
EXPECT_NO_FATAL_FAILURE(stmt) stmt generates no new fatal failures in the current thread
SCOPED_TRACE(msg) Adds file/line/message to every failure in the current scope

6. Mocking with GoogleMock

gMock lets you create mock objects — objects that implement an interface but let you specify at runtime how they should be called and what they should do. Mocks verify the interaction between your code and its collaborators.

Note

A fake has a working (but shortcut) implementation; a mock is pre-programmed with expectations that specify the calls it should receive. For state-based testing, a fake is often the better tool; for interaction-based testing, reach for a mock.

6.1 Defining a mock class

Given an interface (note the virtual destructor — required for any class you inherit from):

class Turtle {
 public:
  virtual ~Turtle() {}
  virtual void PenUp() = 0;
  virtual void PenDown() = 0;
  virtual void Forward(int distance) = 0;
  virtual void Turn(int degrees) = 0;
  virtual void GoTo(int x, int y) = 0;
  virtual int GetX() const = 0;
  virtual int GetY() const = 0;
};

Derive a mock and declare each method with MOCK_METHOD:

#include <gmock/gmock.h>

class MockTurtle : public Turtle {
 public:
  MOCK_METHOD(void, PenUp, (), (override));
  MOCK_METHOD(void, PenDown, (), (override));
  MOCK_METHOD(void, Forward, (int distance), (override));
  MOCK_METHOD(void, Turn, (int degrees), (override));
  MOCK_METHOD(void, GoTo, (int x, int y), (override));
  MOCK_METHOD(int, GetX, (), (const, override));
  MOCK_METHOD(int, GetY, (), (const, override));
};

The MOCK_METHOD signature is:

MOCK_METHOD(ReturnType, MethodName, (ArgTypes...), (Specs...));
Spec Meaning
(override) The method overrides a virtual (recommended)
(const, override) A const method that overrides a virtual
(Calltype(CONV)) A non-default calling convention (e.g. STDMETHODCALLTYPE on Windows)

Important

Only virtual methods can be mocked this way (non-virtual mocking requires a template-based technique). All pure virtual methods of the interface must be mocked or overridden. MOCK_METHOD writes the method definitions for you — no separate implementation needed.

6.2 Using mocks in tests

#include "path/to/mock-turtle.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>

using ::testing::AtLeast;

TEST(PainterTest, CanDrawSomething) {
  MockTurtle turtle;                          // 1. create the mock
  EXPECT_CALL(turtle, PenDown())              // 2. set expectations
      .Times(AtLeast(1));

  Painter painter(&turtle);                   // 3. exercise the code
  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
}
// 4. when `turtle` is destroyed, gMock verifies all expectations were met

If PenDown() is never called, the test fails with a message like:

Actual function call count doesn't match this expectation:
Actually: never called;
Expected: called at least once.

Caution

Set all expectations before the mock is exercised. Do not alternate between EXPECT_CALL() and calling mock methods, and do not set expectations on a mock after passing it to an API. Doing so is undefined behavior. EXPECT_CALL() declares a call expected in the future.

6.3 EXPECT_CALL anatomy

EXPECT_CALL(mock_object, method(matchers))
    .Times(cardinality)
    .WillOnce(action)
    .WillRepeatedly(action);

Matchers specify the expected arguments. A literal value means Eq(value); _ means "any value":

using ::testing::_;
using ::testing::Ge;

EXPECT_CALL(turtle, Forward(100));     // exactly 100
EXPECT_CALL(turtle, GoTo(50, _));      // x = 50, any y
EXPECT_CALL(turtle, Forward(Ge(100))); // at least 100
EXPECT_CALL(turtle, Forward);          // any arguments (non-overloaded only)

Cardinality (Times) says how many calls to expect. If you omit Times(), gMock infers it:

WillOnce / WillRepeatedly present Inferred cardinality
Neither Times(1)
n WillOnce, no WillRepeatedly Times(n)
n WillOnce + one WillRepeatedly Times(AtLeast(n))

Actions say what the method does. WillOnce is consumed once per matching call; WillRepeatedly applies thereafter:

using ::testing::Return;

EXPECT_CALL(turtle, GetX())
    .Times(5)
    .WillOnce(Return(100))
    .WillOnce(Return(150))
    .WillRepeatedly(Return(200));   // 100, 150, 200, 200, 200

Warning

An EXPECT_CALL action clause is evaluated once, even if performed many times. WillRepeatedly(Return(n++)) returns the same value every time — n++ runs once. For per-call side effects, define a custom action.

6.4 Default actions and ON_CALL

A mock function returning void, bool, a number, a pointer, or a default-constructible type has a built-in default action. To set your own default behavior without requiring the call, use ON_CALL:

using ::testing::Return;

ON_CALL(foo, GetSize()).WillByDefault(Return(1));

ON_CALL sets behavior; it does not assert the call happens. Use it for the common case; use EXPECT_CALL when the call must occur.

6.5 Nice, naggy, and strict mocks

Uninteresting calls (calls to methods with no EXPECT_CALL) are handled differently depending on the mock wrapper:

Wrapper Behavior on an uninteresting call
NiceMock<MockFoo> Silently ignored
NaggyMock<MockFoo> Prints a warning (the current default)
StrictMock<MockFoo> Treated as a test failure
using ::testing::NiceMock;
NiceMock<MockFoo> nice_foo;

6.6 Ordered calls

By default calls may happen in any order. To require order, use InSequence:

using ::testing::InSequence;

{
  InSequence seq;
  EXPECT_CALL(turtle, PenDown());
  EXPECT_CALL(turtle, Forward(100));
  EXPECT_CALL(turtle, PenUp());
}
Foo();   // must call the three in this exact order

6.7 Sticky expectations

Important

Expectations are sticky by default — they stay active even after reaching their call upper bound, and gMock matches the last applicable expectation. This is different from many other frameworks. To make an expectation retire once saturated, add .RetiresOnSaturation(), or express ordered behavior with an InSequence.

6.8 Verifying and resetting

using ::testing::Mock;

Mock::VerifyAndClearExpectations(&mock_obj);  // verify + clear expectations
Mock::VerifyAndClear(&mock_obj);              // also clears ON_CALL defaults
Mock::AllowLeak(&mock_obj);                   // don't require verification

6.9 gMock flags

Flag Description
--gmock_catch_leaked_mocks=0 Don't report leaked mock objects as failures
--gmock_verbose=LEVEL Verbosity: info, warning, or error

7. Advanced Testing Features

7.1 Value-parameterized tests

Run the same test logic against many input values. Derive the fixture from testing::TestWithParam<T> and access the value with GetParam():

class FooTest : public testing::TestWithParam<absl::string_view> {};

TEST_P(FooTest, DoesBlah) {
  EXPECT_TRUE(foo.Blah(GetParam()));
}

INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe,
                         FooTest,
                         testing::Values("meeny", "miny", "moe"));

This generates tests named MeenyMinyMoe/FooTest.DoesBlah/0, .../1, .../2.

Parameter generators (all in ::testing):

Generator Yields
Range(begin, end[, step]) {begin, begin+step, ...} excluding end (step defaults to 1)
Values(v1, ..., vN) The listed values
ValuesIn(container) / ValuesIn(begin, end) Values from a container, array, or iterator range
Bool() {false, true}
Combine(g1, ..., gN) The Cartesian product of the generators, as std::tuple
ConvertGenerator<T>(g) Values from g, static_cast from T

Note

INSTANTIATE_TEST_SUITE_P must be at global/namespace scope, not inside a function. A TEST_P with no matching instantiation produces a failing test in the GoogleTestVerification suite; suppress it deliberately with GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); if that's intended.

You can name the generated cases with a fourth argument — a function returning std::string, e.g. the built-in testing::PrintToStringParamName().

7.2 Typed tests

Run the same logic over a fixed list of types known at compile time. Define a fixture template, associate types, and use TYPED_TEST:

template <typename T>
class FooTest : public testing::Test {
 public:
  using List = std::list<T>;
  static T shared_;
  T value_;
};

using MyTypes = ::testing::Types<char, int, unsigned int>;
TYPED_TEST_SUITE(FooTest, MyTypes);

TYPED_TEST(FooTest, DoesBlah) {
  TypeParam n = this->value_;       // TypeParam = the current type
  n += TestFixture::shared_;        // static members via TestFixture::
  typename TestFixture::List values;
}

7.3 Type-parameterized tests

Like typed tests, but you don't need to know the type list up front — define the logic once and instantiate with different types later (useful for interface conformance suites):

TYPED_TEST_SUITE_P(FooTest);
TYPED_TEST_P(FooTest, DoesBlah) { /* ... */ }
TYPED_TEST_P(FooTest, HasPropertyA) { /* ... */ }
REGISTER_TYPED_TEST_SUITE_P(FooTest, DoesBlah, HasPropertyA);

using MyTypes = ::testing::Types<char, int, unsigned int>;
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);

7.4 Death tests

A death test verifies that code terminates (crashes or exits) in an expected way. Name death-test suites with the *DeathTest suffix.

Macro Verifies
EXPECT_DEATH(stmt, matcher) stmt terminates with nonzero exit and stderr matches matcher
EXPECT_DEATH_IF_SUPPORTED(stmt, matcher) Same, but a no-op where death tests aren't supported
EXPECT_DEBUG_DEATH(stmt, matcher) Acts like EXPECT_DEATH in debug builds; just runs stmt when NDEBUG
EXPECT_EXIT(stmt, predicate, matcher) Exit status satisfies predicate and stderr matches matcher
TEST(MyDeathTest, Foo) {
  ASSERT_DEATH({
    int n = 5;
    Foo(&n);
  }, "Error on line .* of Foo()");
}

TEST(MyDeathTest, NormalExit) {
  EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");
}

TEST(MyDeathTest, KillProcess) {
  EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL),
              "Sending myself unblockable signal");
}

Caution

The matcher in a death assertion is treated as a regular expression (ContainsRegex), not an exact string. A bare string s means ContainsRegex(s), not Eq(s).

Warning

Death tests run the statement in a child process, so any in-memory side effects (state changes, memory frees) are not visible in the parent. If your death test uses mocks, move the EXPECT_CALL statements inside the EXPECT_DEATH macro, or the parent won't see the calls.

The --gtest_death_test_style flag (or GTEST_FLAG_SET(death_test_style, ...)) chooses "fast" (default) or "threadsafe" (slower but safer with threads).

7.5 Skipping tests at runtime

GTEST_SKIP() stops the current test (or, in a fixture/environment SetUp(), skips its whole suite or program):

TEST(SkipTest, DoesSkip) {
  GTEST_SKIP() << "Skipping single test";
  FAIL();  // Not executed
}

7.6 Global setup and teardown

Subclass testing::Environment for program-wide setup/teardown, and register it before RUN_ALL_TESTS() (preferably in your own main()):

class MyEnv : public ::testing::Environment {
 public:
  void SetUp() override { /* ... */ }
  void TearDown() override { /* ... */ }
};

testing::AddGlobalTestEnvironment(new MyEnv);

Note

GoogleTest takes ownership of the registered environment — do not delete it yourself. Multiple environments set up in registration order and tear down in reverse.

7.7 Per-test-suite shared resources

For resources too expensive to rebuild per test, use static members plus SetUpTestSuite() / TearDownTestSuite() (mind the capital U):

class FooTest : public testing::Test {
 protected:
  static void SetUpTestSuite() { shared_resource_ = new T(...); }
  static void TearDownTestSuite() { delete shared_resource_; shared_resource_ = nullptr; }
  static T* shared_resource_;
};
T* FooTest::shared_resource_ = nullptr;

Caution

Tests run in an undefined order, so they must not depend on each other and must restore any shared state they modify.

7.8 Teaching GoogleTest to print your types

When an assertion fails, GoogleTest prints the values. Teach it to print your type nicely by defining a friend AbslStringify() (preferred) or PrintTo():

class Point {
  friend void PrintTo(const Point& p, std::ostream* os) {
    *os << "(" << p.x << "," << p.y << ")";
  }
  int x, y;
};

You can also call testing::PrintToString(x) directly to format any value.

7.9 Tracing into subroutines

When an assertion inside a helper fails, SCOPED_TRACE tells you which call site it came from:

SCOPED_TRACE("A");   // file, line, and "A" appended to every failure in scope

8. Matchers Reference

Matchers validate a single argument inside EXPECT_THAT, ON_CALL, or EXPECT_CALL. All live in ::testing. (This is a working subset; the framework provides more.)

8.1 Wildcards and generic comparison

Matcher Matches when
_ Any value of the right type
A<T>() / An<T>() Any value of type T
Eq(v) or v argument == v
Ne(v), Lt(v), Le(v), Gt(v), Ge(v) !=, <, <=, >, >=
IsNull() / NotNull() Argument is / isn't a null pointer
IsTrue() / IsFalse() Evaluates true / false in boolean context
Ref(var) Argument is a reference to var
Optional(m) An optional<> containing a value matching m
VariantWith<T>(m) / AnyWith<T>(m) A variant/any holding a T matching m

8.2 Floating-point matchers

Matcher Matches
FloatEq(f) / DoubleEq(d) Approximately equal (NaN ≠ NaN)
NanSensitiveFloatEq(f) / NanSensitiveDoubleEq(d) Approximately equal, NaN == NaN
FloatNear(f, err) / DoubleNear(d, err) Within err
IsNan() Any floating-point NaN

8.3 String matchers

Matcher Matches
StrEq(s) / StrNe(s) Equal / not equal
StrCaseEq(s) / StrCaseNe(s) Equal / not equal, ignoring case
HasSubstr(s) Contains s
StartsWith(p) / EndsWith(s) Prefix / suffix
MatchesRegex(re) / ContainsRegex(re) Full / partial regex match
IsEmpty() Empty string

8.4 Container matchers

Matcher Matches
ElementsAre(e0, ..., en) Exactly these elements in order
ElementsAreArray(...) Like ElementsAre but from a container/array/range
UnorderedElementsAre(...) These elements in any order
Contains(e) Contains an element matching e (.Times(n) to count)
Each(e) Every element matches e
SizeIs(m) Size matches m
IsEmpty() container.empty()
IsSubsetOf(...) / IsSupersetOf(...) Subset / superset relation
Pointwise(m, c) Element-wise 2-tuple match against c
WhenSorted(m) Matches m after sorting

8.5 Member, pointer, and composite matchers

Matcher Matches
Field(&Class::field, m) argument.field matches m
Property(&Class::prop, m) argument.prop() matches m (const, no-arg method)
Key(m) / Pair(m1, m2) Map key / std::pair fields
Pointee(m) The value a pointer points to matches m
ResultOf(f, m) f(argument) matches m
AllOf(m1, ..., mn) Matches all of them
AnyOf(m1, ..., mn) Matches at least one
Not(m) Doesn't match m
Truly(predicate) predicate(argument) is truthy

8.6 Defining custom matchers

MATCHER(IsEven, "") { return (arg % 2) == 0; }
MATCHER_P(IsDivisibleBy, n, "") { return (arg % n) == 0; }

Note

MATCHER* macros cannot be used inside a function or class, and the body must be purely functional (no side effects).


9. Actions Reference

Actions specify what a mock function does when invoked. All live in ::testing.

9.1 Returning values

Action Effect
Return() Return from a void function
Return(value) Return value (converted at expectation-set time)
ReturnArg<N>() Return the N-th argument
ReturnRef(var) Return a reference to var
ReturnPointee(ptr) Return *ptr
ReturnNull() Return a null pointer
ReturnRoundRobin({...}) Cycle through the listed values

9.2 Side effects

Action Effect
Assign(&var, value) Set var = value
SaveArg<N>(ptr) Copy the N-th argument to *ptr
SetArgPointee<N>(value) Set *arg_N = value
SetArrayArgument<N>(first, last) Copy a range into the N-th argument
Throw(exception) Throw the given exception

Important

SetArgPointee<N>() only sets a side effect — it doesn't supply a return value. Combine it with Return via DoAll: WillOnce(DoAll(SetArgPointee<0>(5), Return(true))).

9.3 Calling functions and composing actions

Action Effect
Invoke(f) / f Call f with the mock's arguments
InvokeWithoutArgs(f) Call f with no arguments
InvokeArgument<N>(args...) Call the N-th argument (a callable) with args
DoAll(a1, ..., an) Do all; return the result of an
DoDefault() Perform the default action
WithArg<N>(a) / WithArgs<N...>(a) Forward selected args to action a
ACTION(Sum) { return arg0 + arg1; }   // custom action (file/namespace scope)

10. Running Tests from the Command Line

GoogleTest binaries are ordinary executables. Control them with command-line flags (requires InitGoogleTest()) or environment variables. A flag takes precedence over the matching environment variable.

Run your_test --help to list all flags.

10.1 Selecting tests

Flag Effect
--gtest_list_tests List all tests without running them
--gtest_filter=PATTERN Run only tests whose full name matches
--gtest_also_run_disabled_tests Include DISABLED_ tests
--gtest_fail_fast Stop at the first failure

Filter syntax is :-separated wildcard patterns, optionally followed by - and negative patterns. * matches any string, ? any single character:

./foo_test --gtest_filter=FooTest.*            # all of FooTest
./foo_test --gtest_filter=*Null*:*Constructor* # names containing Null or Constructor
./foo_test --gtest_filter=-*DeathTest.*        # all non-death tests
./foo_test --gtest_filter=FooTest.*-FooTest.Bar  # FooTest except Bar

10.2 Disabling tests

Prefix a test or suite name with DISABLED_ to exclude it from runs while keeping it compiled (so it can't rot):

TEST(FooTest, DISABLED_DoesAbc) { ... }
class DISABLED_BarTest : public testing::Test { ... };

GoogleTest prints a banner warning when disabled tests exist.

10.3 Repeating and shuffling

Flag Effect
--gtest_repeat=N Repeat tests N times (-1 = forever)
--gtest_break_on_failure Drop into the debugger on failure (great with --gtest_repeat)
--gtest_shuffle Run tests in random order (reveals inter-test dependencies)
--gtest_random_seed=SEED Fix the shuffle seed (0 = time-based)
foo_test --gtest_repeat=1000 --gtest_break_on_failure   # hunt a flaky test

10.4 Controlling output

Flag Effect
--gtest_color=(yes|no|auto) Colored terminal output
--gtest_brief=1 Print only failures
--gtest_print_time=0 Suppress per-test timing
--gtest_output=xml[:path] Emit a JUnit-style XML report
--gtest_output=json[:path] Emit a JSON report
--gtest_catch_exceptions=0 Let the debugger handle thrown exceptions
foo_test --gtest_output=xml:results/      # writes results/foo_test.xml

10.5 Sharding (parallel across machines)

A test runner can split tests across machines by setting environment variables on each shard:

Variable Meaning
GTEST_TOTAL_SHARDS Total number of shards (same on all)
GTEST_SHARD_INDEX This shard's index, 0..TOTAL-1
GTEST_SHARD_STATUS_FILE A path the binary touches to acknowledge sharding support

10.6 Common environment variables

Most flags have a matching GTEST_-prefixed environment variable, e.g. GTEST_FILTER, GTEST_REPEAT, GTEST_SHUFFLE, GTEST_COLOR, GTEST_OUTPUT, GTEST_BREAK_ON_FAILURE, GTEST_CATCH_EXCEPTIONS, GTEST_ALSO_RUN_DISABLED_TESTS, GTEST_FAIL_FAST, GTEST_PRINT_TIME.


11. Learning from the Samples

The googletest/samples/ directory contains well-commented examples, each demonstrating a feature:

Sample Demonstrates
Sample #1 Basic steps of testing C++ functions
Sample #2 A more complex unit test for a class with multiple methods
Sample #3 Using a test fixture
Sample #4 Combining GoogleTest features
Sample #5 Sharing logic via a base fixture, reused in derived fixtures
Sample #6 Type-parameterized tests
Sample #7 Value-parameterized tests
Sample #8 Combine() in value-parameterized tests
Sample #9 The listener API to customize console output + the reflection API
Sample #10 The listener API to implement a memory-leak checker

12. Troubleshooting

Error: void value not ignored as it ought to be

Cause: You used an ASSERT_*() (or FAIL()) in a function that does not return void. Fatal assertions are only valid in void-returning functions because exceptions are disabled.

Solution: Either switch to the EXPECT_* variant, or refactor so the fatal assertion lives in a void helper (return results via an out-parameter).

Prevention: Keep fatal assertions in test bodies and void helpers; never in constructors, destructors, or value-returning functions.

Error: ignoring return value of 'int RUN_ALL_TESTS()'

Cause: Your main() calls RUN_ALL_TESTS() without using its return value.

Solution: return RUN_ALL_TESTS();

Prevention: Prefer linking gtest_main so you don't write main() at all.

Error: no matching function for call to 'FooTest::FooTest()'

Cause: Your fixture lacks a default constructor (e.g. you declared a non-default one, or it has a const non-static member).

Solution: Define a default constructor; if there's a const member, initialize it in the constructor's initializer list.

Error: My SetUp() function is not called

Cause: You spelled it Setup() (lower-case u), or spelled SetUpTestSuite() as SetupTestSuite(). C++ is case-sensitive.

Solution: Use the exact spelling SetUp() / SetUpTestSuite() and add override so the compiler catches the typo.

Error: undefined reference to a static const member

Cause: You declared a static const int kBar = 100; in the class body and used it in an assertion (which takes its address), but never defined it.

Solution: Add a definition in the .cc file: const int Foo::kBar; (no initializer). Or declare it static constexpr, which is implicitly inline.

Error: no match for 'operator<<' in an assertion

Cause: You compared a user-defined type, but it has no std::ostream& operator<<(std::ostream&, const FooType&).

Solution: Define operator<< (in the same namespace as the type), or teach GoogleTest to print it with a friend AbslStringify() / PrintTo().

Error: Use of deleted function / build failures with new compilers

Cause: Newer compilers (e.g. GCC 15) tighten language rules; some older patterns no longer compile (community issues #4965, #4881, #4759).

Solution: Track the latest GoogleTest release, which carries fixes for new compiler versions. Ensure your build uses C++17 or newer.

Problem: My death test hangs or seg-faults

Cause: Death tests dislike multiple threads in the parent process; forking with threads is fragile.

Solution: Eliminate threads created before main()/outside EXPECT_DEATH, move as much as possible inside EXPECT_DEATH, or set --gtest_death_test_style=threadsafe (slower but safer). Thread-safe death tests re-run the program from the start in the child, so your program must be deterministic and able to run side-by-side with itself.

Problem: My death test's state change is lost

Cause: Death tests run in a child process; in-memory side effects aren't visible to the parent.

Solution: This is by design. If the death test uses mocks, move the EXPECT_CALLs inside EXPECT_DEATH so they execute in the child.

Problem: pkg-config can't find GoogleTest

Cause: You installed GoogleTest manually and pkg-config doesn't know where the .pc files are.

Solution: export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig (adjust to your install prefix).

Problem: gMock warns "Uninteresting mock function call"

Cause: A mocked method with no EXPECT_CALL was called. gMock treats it as allowed but warns ("naggy" behavior).

Solution: If the call is fine, either wrap the mock in NiceMock<...> or add EXPECT_CALL(mock, Method(_)).Times(AnyNumber()). If it shouldn't happen, add .Times(0). Lower noise with --gmock_verbose=error.

Problem: The method on the real object runs instead of the mock

Cause: The method isn't virtual. Only virtual methods are mocked through MOCK_METHOD.

Solution: Make the interface method virtual (and give the base class a virtual destructor), or use the high-performance non-virtual mocking technique.

Problem: GoogleTest output is buried in LOG messages

Cause: Your test logs to stderr, mixing with framework output.

Solution: GoogleTest writes to stdout; redirect it separately: ./my_test > gtest_output.txt.


13. FAQ

Q: Why can't test suite and test names contain underscores? C++ reserves identifiers with __ anywhere or a leading _ + uppercase letter. TEST(Suite, Name) generates a class Suite_Name_Test, so stray underscores can produce reserved/invalid names — and TEST(Time, Flies_Like_An_Arrow) could collide with TEST(Time_Flies, Like_An_Arrow). The simple rule avoids all of it.

Q: Why is there EXPECT_EQ(NULL, ptr) but no EXPECT_NE(NULL, ptr)? Supporting NULL requires template metaprogramming that the maintainers only added where most needed. Prefer nullptr: EXPECT_EQ(ptr, nullptr) and EXPECT_NE(ptr, nullptr) both work. Or use EXPECT_THAT(ptr, NotNull()).

Q: Should I use the constructor/destructor or SetUp()/TearDown()? Prefer the constructor/destructor (enables const members, correct base-class ordering). Use SetUp()/TearDown() when you need a virtual call, a fatal assertion during setup, or exception-safe teardown.

Q: Typed tests or value-parameterized tests for testing interface implementations? Typed tests are easier when all implementations are created the same way (modulo type) and give type names in failures. Value-parameterized tests are easier when construction differs per implementation, and are less error-prone about testing against the interface type. When unsure, try both.

Q: Can I derive one test fixture from another? Yes — put shared logic in a base fixture and derive per-suite fixtures. There's no depth limit. Remember to chain base SetUp()/TearDown().

Q: Can two TEST(Foo, Bar) exist in different namespaces? Yes. The rule is that all tests in the same test suite must use the same fixture class. Two plain TEST(CoolTest, ...) are fine (both use ::testing::Test); two TEST_F with same-named but different fixture classes in different namespaces is a runtime error.

Q: How do I run only a subset of tests? Use --gtest_filter, e.g. --gtest_filter=FooTest.*-FooTest.Bar.

Q: How do I temporarily disable a test? Prefix its name with DISABLED_. Re-enable all such tests with --gtest_also_run_disabled_tests.

Q: How can my code detect it's running in a test? It shouldn't — that leaks test logic into production and invites Heisenbugs. GoogleTest deliberately offers no API for it. Use dependency injection instead.

Q: Can I mock a non-virtual or static function? Not directly with MOCK_METHOD. Non-virtual methods need a template-based technique; static/global functions usually indicate tight coupling — wrap them behind a small interface and mock that.

Q: Can I mock a variadic function? Not directly — a mock can't know how many ... arguments were passed or their types. Provide overloaded, non-variadic versions to mock instead.

Q: How do I assert a function is never called? EXPECT_CALL(foo, Bar(_)).Times(0);

Q: Why does gMock match the newest expectation first? So you can set common defaults early (constructor/SetUp()) and override with specific expectations in the test body. Put more specific matchers after general ones.

Q: How do I see gMock's call trace when debugging unmet expectations? Run with --gmock_verbose=info to print every mock call gMock receives.

Q: Which projects use GoogleTest? Chromium, LLVM, Protocol Buffers, and OpenCV, among many others.