GoogleTest: Google's C++ Testing and Mocking Framework
GitHub Repo
BSD-3-Clause
November 16, 2026 at 01:54 PM
0 views

GoogleTest: Google's C++ Testing and Mocking Framework

@googleProject Author

What GoogleTest is

GoogleTest is Google's C++ testing framework. The repository's README calls itself "a merger of the formerly separate GoogleTest and GoogleMock projects", which "were so closely related that it makes sense to maintain and release them together". One checkout therefore gives two libraries: gtest, an xUnit-style test runner with assertions, fixtures, parameterized tests and death tests, and gMock, a framework for writing C++ mock classes and setting expectations on how they are called. Both are built and installed by the same CMake project or Bazel module.

The primer says the framework was "developed by the Testing Technology team with Google's specific requirements and constraints in mind" and that it "supports any kind of tests, not just unit tests". The design goals it lists are concrete: tests should be independent and repeatable (each test runs on a fresh fixture object), organised into suites, portable across operating systems and compilers "with or without exceptions", informative when they fail (a failing test does not stop the run), free of housekeeping (tests register themselves) and fast (shared resources can be set up once per suite). The README names Chromium, LLVM, Protocol Buffers and OpenCV as notable users outside Google.

The project is licensed under the BSD 3-Clause licence (copyright Google Inc.), written in C++, and developed on the main branch of google/googletest. The documentation lives as Markdown under docs/ in the repository and is published at google.github.io/googletest.

How it works

Tests, suites and fixtures

A test is a function defined with the TEST(SuiteName, TestName) macro. The FAQ explains what happens underneath: the macro generates a class named TestSuiteName_TestName_Test and registers an instance with the framework, which is why suite and test names should not contain underscores (C++ reserves identifiers with a leading underscore and capital letter or a double underscore, and GoogleTest reserves the DISABLED_ prefix). Tests that need shared setup derive a fixture class from testing::Test and use TEST_F; every test gets a fresh fixture object, so state does not leak between tests. The primer points out a terminology change: older versions said "test case" for a group of tests, and the project has been switching to "test suite" to match the ISTQB meaning.

Assertions: EXPECT versus ASSERT

Assertions are macros that come in pairs. EXPECT_* records a non-fatal failure and lets the test continue; ASSERT_* records a fatal failure and returns from the current function. The primer recommends EXPECT_* by default "as they allow more than one failure to be reported in a test", and warns that a failed ASSERT_* can skip clean-up code. Any value that can be streamed to an ostream can be appended to a failure message with <<. The assertions reference covers boolean, comparison, string, floating-point, exception, predicate and death assertions, and gMock matchers can be used inside EXPECT_THAT.

Mocks with gMock

gMock generates mock implementations of virtual methods. The gMock README lists jMock, EasyMock and Hamcrest as inspirations and says it provides a declarative syntax, partial (hybrid) mocks, support for overloaded functions, a matcher library, automatic verification of expectations ("no record-and-replay needed"), ordering constraints, and that it "does not use exceptions". A mock is a subclass that declares each method with MOCK_METHOD; a test then sets expectations with EXPECT_CALL and actions such as Return. The cookbook describes three strictness levels: a plain mock prints a warning on an "uninteresting call" (a call with no matching expectation), NiceMock stays quiet and StrictMock turns such calls into failures.

Death tests and process isolation

Death tests check that code terminates the process in an expected way, for example via abort() in a failed precondition check. The advanced guide says the statement runs in a child process, so side effects are not visible to the parent; on Linux GoogleTest uses clone() rather than fork(). Because forking in a multithreaded process is risky, test suites whose name ends in DeathTest are run before all other tests, a warning is printed if multiple threads are running, and a slower "threadsafe" style can be selected with GTEST_FLAG_SET(death_test_style, "threadsafe").

The test binary as a CLI

A GoogleTest program is an ordinary executable. When it calls testing::InitGoogleTest() (the bundled gtest_main and gmock_main libraries do this), it accepts flags and matching environment variables: --gtest_filter / GTEST_FILTER, --gtest_repeat, --gtest_shuffle with --gtest_random_seed, --gtest_fail_fast, --gtest_list_tests, --gtest_output=xml: or json:, and sharding through GTEST_TOTAL_SHARDS and GTEST_SHARD_INDEX. When a flag and an environment variable are both set, the flag wins.

Key features

  • Automatic test discovery. Tests register themselves at static-initialisation time; nothing has to be listed by hand, and RUN_ALL_TESTS() runs everything that was linked in.
  • Fatal and non-fatal assertions. Paired ASSERT_* and EXPECT_* macros let a test either stop or continue after a failure, with custom messages streamed in.
  • Fixtures and shared resources. TEST_F fixtures get SetUp()/TearDown(), and per-suite or global environments can pay an expensive set-up cost once.
  • Value-parameterized tests. TEST_P plus INSTANTIATE_TEST_SUITE_P runs one test body against a list or generator of values, with optional custom names for each instance.
  • Typed and type-parameterized tests. The same test logic can run across a list of types, either known up front (typed tests) or supplied later by users of an interface (type-parameterized tests).
  • Death tests. EXPECT_DEATH, EXPECT_EXIT and their ASSERT_ forms check exit codes, signals and stderr output of code that terminates the process.
  • gMock. MOCK_METHOD, EXPECT_CALL, ON_CALL, cardinalities, sequences, matchers and actions, with nice, naggy and strict mock modes.
  • Run control. Filters with positive and negative wildcard patterns, repetition (including forever with a negative count), shuffling with a reproducible seed, fail-fast, and disabled tests via the DISABLED_ prefix.
  • Machine-readable reports. XML output based on the Ant junitreport format and a JSON report, both with per-test durations.
  • Sharding protocol. Runners set two environment variables and each shard picks a disjoint subset; a status file lets the runner detect whether a binary understands the protocol.
  • Event listeners and sanitizer hooks. Custom listeners can observe the run, and the advanced guide shows how to turn UBSan, ASan and TSan reports into test failures.
  • pkg-config and CMake packages. An install exports GTest::gtest, GTest::gmock and the _main variants for find_package, plus .pc files for other build systems.

Getting started

Two quickstarts ship in the repository, one for CMake and one for Bazel. Both require a compiler that supports at least C++17. The CMake route pulls GoogleTest into the build with FetchContent. The quickstart's CMakeLists.txt is:

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)

A first test, hello_test.cc, from the same page:

#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);
}

The quickstart then appends the test target and CTest discovery to CMakeLists.txt:

enable_testing()

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

include(GoogleTest)
gtest_discover_tests(hello_test)

and builds and runs it with:

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

For Bazel (the quickstart asks for Bazel 7.0 or later and calls Bazel "the preferred build system used by the GoogleTest team"), the dependency comes from the Bazel Central Registry:

bazel_dep(name = "googletest", version = "1.18.0")

with a cc_test rule in BUILD:

cc_test(
    name = "hello_test",
    size = "small",
    srcs = ["hello_test.cc"],
    deps = [
        "@googletest//:gtest",
        "@googletest//:gtest_main",
    ],
)
bazel test --cxxopt=-std=c++17 --test_output=all //:hello_test

To build and install GoogleTest as a standalone project, googletest/README.md gives:

git clone https://github.com/google/googletest.git -b v1.18.0
cd googletest        # Main directory of the cloned repository.
mkdir build          # Create a directory to hold the build output.
cd build
cmake ..             # Generate native build scripts for GoogleTest.

followed by make and sudo make install, after which a consuming project can use find_package(GTest CONFIG REQUIRED) and link GTest::gtest or GTest::gmock. Passing -DBUILD_GMOCK=OFF builds only gtest. A minimal mock from "gMock for Dummies" looks like this:

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));
};

Filter and repeat syntax from the advanced guide, useful once a suite grows:

./foo_test --gtest_filter=FooTest.*-FooTest.Bar
./foo_test --gtest_filter=-*DeathTest.*
$ foo_test --gtest_repeat=1000 --gtest_break_on_failure

Hands-on: GoogleTest 1.18.0 with CMake and GCC 13

The following was run on 16 November 2026 on a 2-vCPU x86_64 cloud VM running Ubuntu 24.04.5 LTS, with GCC 13.3.0, CMake 3.28.3 and GNU Make. The VM's network policy blocked github.com downloads (archives, release assets and git clone), so the v1.18.0 sources were fetched file by file from raw.githubusercontent.com at the v1.18.0 tag: 67 files, 1.8 MB, starting from the top-level CMakeLists.txt and following every #include from gtest-all.cc, gmock-all.cc and the two main files. This is a smoke test, not a benchmark, and timings are single runs.

Building the library

StepResult
Version in top-level CMakeLists.txtset(GOOGLETEST_VERSION 1.18.0), cmake_minimum_required(VERSION 3.16), and a comment: "CMake support is community-based. The maintainers do not use CMake internally."
cmake .. (standalone, gMock on by default)Configured in 0.5 s; compiler detected as GNU 13.3.0; pthread found in libc
make -j26.3 s wall clock for all four libraries
Static libraries (default build type, no optimisation flags)libgtest.a 2,783,072 bytes, libgmock.a 784,602 bytes, libgtest_main.a 3,212 bytes, libgmock_main.a 3,500 bytes
make install to a local prefix4.6 MB: headers under include/gtest and include/gmock, CMake package files under lib/cmake/GTest, and four pkg-config files (gtest.pc, gtest_main.pc, gmock.pc, gmock_main.pc)

The quickstart, verbatim

Running the CMake quickstart exactly as written failed at configure time in this VM: FetchContent tried to download the pinned commit archive from github.com and stopped with "Each download failed!" and HTTP/1.1 403 Forbidden. Projects whose CI runners have no access to github.com hit the same wall. CMake's standard FETCHCONTENT_SOURCE_DIR_GOOGLETEST cache variable, pointed at the local v1.18.0 checkout, made the unchanged CMakeLists.txt work: configure took 0.36 s, the build 5.8 s (it builds gmock and gmock_main too, as the quickstart's sample output shows), the hello_test binary was 1,122,880 bytes, and ctest reported 100% tests passed, 0 tests failed out of 1. CMake 3.28 also printed a developer warning that the DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy CMP0135 was not set; it is harmless but appears on every fresh configure with the quickstart file.

A larger test binary

A second project used the installed package through find_package(GTest CONFIG REQUIRED) and linked GTest::gmock_main. Its single test file contained a plain TEST, a TEST_F fixture holding a gMock mock of a currency-rate interface (one test expecting Rate("EUR", "USD") exactly once and returning 1.5, one expecting zero calls, one using EXPECT_THROW), a value-parameterized suite instantiated with four values, a death test that expects abort() with a message matched through HasSubstr, and one deliberately failing EXPECT_EQ. Built as Release.

Command or checkResult (trimmed)
Compile and link one test file2.7 s; binary 1,526,296 bytes, 854,360 bytes after strip
./demo_testRunning main() from gmock_main.cc, then 10 tests from 5 test suites ran. (1 ms total), [ PASSED ] 9 tests., 1 FAILED TEST, exit code 1
Order of executionCheckedDeathTest ran first even though it was defined after the other suites in the file, matching the documented rule for suites ending in DeathTest
Failure messageExpected equality of these values: followed by each expression and Which is: 1 / Which is: 2, then the streamed text map was 1
--gtest_list_testsSuites and tests without running them; parameterized instances shown as IsEven/0 # GetParam() = 0 and so on
--gtest_filter='-Failing.*'9 tests from 4 suites, all passed, exit code 0
--gtest_brief=1 with a two-pattern filterOnly the summary lines: 7 tests from 2 test suites ran, [ PASSED ] 7 tests.
--gtest_repeat=1000 on the 9 passing tests0.37 s total; the same run without the death test took 0.035 s, so the forked death test dominated the cost
--gtest_shuffle --gtest_random_seed=42Printed Randomizing tests' orders with a seed of 42; tests inside each suite were reordered, the death-test suite still came first
Sharding: GTEST_TOTAL_SHARDS=3, index 0, 1, 24, 3 and 3 tests respectively; every test ran exactly once across the three shards
--gtest_output=xml:report.xml3,341-byte JUnit-style file with tests="10" failures="1", a file and line attribute per test case, and every time attribute written as "0." because each test took under a millisecond
--gtest_output=xml:out/, run twiceout/demo_test.xml and then out/demo_test_1.xml; the second run did not overwrite the first
--gtest_output=json:report.jsonTop level tests: 10, failures: 1, time: "0s", UTC timestamp
ctest via gtest_discover_testsTen CTest entries, 90% tests passed, 1 tests failed out of 10
--help23 lines mentioning a --gtest_ flag

Three things stood out. First, CTest named the parameterized tests by parameter value (Small/EvenTest.IsEven/4, IsEven/6) while the test binary itself names them by index (IsEven/2, IsEven/3), so a name copied from a CTest report does not always work as a --gtest_filter pattern. Second, a separate mock test showed gMock's three behaviours: an expectation of two calls that received one failed with Expected: to be called twice / Actual: called once - unsatisfied and active; an unexpected call on a plain mock passed with a GMOCK WARNING: Uninteresting mock function call - returning default value. block; the same call on a NiceMock printed nothing. The wording differs slightly from the sample failure in "gMock for Dummies", so tooling that greps failure text should be checked against the real output. Third, compiling the same file with -std=c++14 stopped immediately at gtest-port.h with #error C++ versions less than C++17 are not supported., so the C++17 floor is enforced, not just documented.

Where GoogleTest fits

  • Unit tests for C++ libraries and services. The default use: one or more test binaries per module, linked against gtest_main, registered with CTest or Bazel's cc_test.
  • Isolating dependencies with mocks. Code written against virtual interfaces (storage, network clients, clocks) can be tested with gMock expectations instead of real backends.
  • Checking crash and precondition paths. Death tests cover code that is supposed to abort or exit, which most frameworks leave untested.
  • Flaky-test hunting. --gtest_repeat with --gtest_break_on_failure under a debugger, or with --gtest_shuffle to expose order dependencies, is documented exactly for this.
  • CI pipelines. XML or JSON reports, a non-zero exit code on failure and the sharding protocol let a CI system split and collect test runs. On Jenkins, the JUnit plugin's README describes a publisher that "consumes XML test reports generated during the builds", which is where the XML output fits, and workflows can be rehearsed locally with act before they run in GitHub Actions.
  • Bazel monorepos. The team calls Bazel its preferred build system, and the module is published to the Bazel Central Registry, which lists versions up to 1.18.0.bcr.1.
  • Testing code that uses other C++ libraries. GoogleTest sits next to dependencies such as nlohmann/json in the same CMake or vcpkg build; the vcpkg port is named gtest and was at 1.18.0 on the day of checking.

How GoogleTest compares

The README of doctest lists googletest alongside Catch, Boost.Test, UnitTest++ and cpputest as the established C++ test frameworks. Catch2 and doctest are the two most often weighed against GoogleTest. The table below is limited to what each project's own README, licence file or packaging metadata says; none of the three was benchmarked here, and neither alternative currently has a page in this directory.

AspectGoogleTest 1.18.0Catch2 (v3 line, vcpkg 3.16.1)doctest (vcpkg 2.5.3)
LicenceBSD-3-ClauseBoost Software License 1.0MIT
Minimum C++ standardC++17 (since the 1.17.x line)C++14, per its "why Catch" pageC++11, per its README badge and feature list
PackagingCompiled libraries (gtest, gmock, _main variants); CMake, Bazel, pkg-configREADME says v3 is "no longer a single-header library" and now has separately compiled implementationSingle header, doctest.h
Test stylexUnit macros: TEST, TEST_F, TEST_P, paired EXPECT_/ASSERT_TEST_CASE with free-form names and tags, assertions as plain boolean expressions, sections for shared set-upSelf-registering tests that can live inside production source files
MockingBuilt in (gMock)Not described in the README pages readNot described in the README pages read
Death testsBuilt inNot described in the README pages readNot described in the README pages read
Other extrasValue- and type-parameterized tests, sharding, XML/JSON reportsMicro-benchmarking and BDD macros, per its READMEREADME claims the fastest compile times and runtime among feature-rich frameworks (its own benchmarks)

In short: GoogleTest is the broadest of the three out of the box, chiefly because gMock and death tests ship with it, and it has the strongest Bazel story. Its costs are a newer C++ floor and a compiled library to build. Catch2's selling points are natural test syntax and sections; doctest's are a single header, C++11 support and compile speed. Projects that already use GoogleTest's mocking often keep it for that reason alone, and nothing stops a codebase from using gMock's matchers inside GoogleTest while another component uses a different runner.

Limits and when not to use it

  • C++17 is mandatory. The README says the 1.18.x branch "requires at least C++17", and the hands-on build showed a hard #error under C++14. Codebases stuck on C++11 or C++14 compilers need an older release or another framework.
  • CMake is not the maintainers' build. The top-level CMakeLists.txt says CMake support "is community-based" and that the maintainers "do not use CMake internally"; Bazel is the preferred system. The quickstart also declares cmake_minimum_required(VERSION 3.14) while GoogleTest's own CMakeLists.txt requires 3.16.
  • Network-dependent quickstart. The recommended FetchContent setup downloads from github.com at configure time. In locked-down CI that fails, as it did here, unless the source is vendored, mirrored or overridden. The quickstart and googletest/README.md also pin different example commits (03597a01… and 5376968f…), and both say to update the hash regularly, which is manual work.
  • Abseil is coming. The README's "Coming Soon" section says the project plans to take a dependency on Abseil. The Bazel module on main already declares abseil-cpp and re2, and CMake has an off-by-default GTEST_HAS_ABSL option. Teams that want a dependency-free test framework should watch this.
  • Thread-safety outside pthreads. The primer's known limitations say assertions are thread-safe only where pthreads are available and "currently unsafe" from two threads concurrently on other systems such as Windows.
  • Death-test caveats. Death tests fork or clone, which the docs warn is risky in multithreaded processes; side effects in the child are invisible to the parent; two death assertions cannot share one source line; and mocks inside a death test that expects a specific exit code must be leaked with Mock::AllowLeak. The docs add that clone(), which Linux uses because fork() is more likely to hang a multithreaded parent, is not available on Cygwin and macOS.
  • Mocking needs virtual interfaces. gMock mocks virtual methods by subclassing; non-virtual or free functions need extra indirection (the cookbook covers workarounds), which can push design changes into production code.
  • Contribution model. CONTRIBUTING asks for a signed Google CLA and asks Googlers to submit changes internally rather than as GitHub pull requests, and the README says continuous integration runs on Google's internal systems. External contributors see less of the review process than in community-run projects.
  • Parallelism mostly comes from outside. The README's feature list mentions running tests in parallel, but the mechanisms the docs describe are the sharding protocol and external runners: the README lists gtest-parallel as a separate project, and the --help output of the 1.18.0 test binary showed no parallel-execution flag. CTest's -j or Bazel can run discovered tests concurrently.

Ecosystem and related tools

The README lists several third-party projects around GoogleTest: GTest Runner (a Qt5 GUI runner for Windows and Linux), GoogleTest UI (a C# runner with a progress bar), GTest TAP Listener (an event listener that emits TAP output), gtest-parallel (runs tests from one binary in parallel), two VS Code extensions (GoogleTest Adapter and C++ TestMate) that show tests in a tree view, and Cornichon, a Gherkin parser that generates GoogleTest stubs. Beyond those, the CMake GoogleTest module's gtest_discover_tests (used in the quickstart and in the hands-on run) turns each test in a binary into a CTest entry, and the pkg-config files let Meson, Autotools or plain Makefiles find the libraries; the pkg-config page recommends using the full _CFLAGS and _LDFLAGS rather than include directories and library names alone, because GoogleTest may need macros and -pthread.

Macro name clashes with other libraries are handled with GTEST_DONT_DEFINE_FOO=1 switches (for example -DGTEST_DONT_DEFINE_TEST=1 renames TEST to GTEST_TEST), and shared-library builds use GTEST_CREATE_SHARED_LIBRARY and GTEST_LINKED_AS_SHARED_LIBRARY. The generic build README notes that GoogleTest is "compact", so most users link it statically.

Project activity

Checked 16 November 2026: latest release v1.18.0, announced in the README and matched by the vcpkg port, the Homebrew formula and the Bazel Central Registry, published on 10 August 2026 according to the GitHub releases API; licence BSD-3-Clause; about 39,700 stars and 11,000 forks on google/googletest, with the last push on 13 November 2026. The repository was created on 28 July 2015, is written in C++, and develops on main. Documentation is at google.github.io/googletest, with the sources in the repository's docs/ folder.

Enjoying this project?

Discover more amazing open-source projects on TechLogHub. We curate the best developer tools and projects.

Project
googletest
Created
November 16
Last Updated
November 16, 2026 at 01:54 PM

Maintain GoogleTest: Google's C++ Testing and Mocking Framework? Add the badge to your README

Show that the project is featured on TechLogHub and send readers to this write-up.

Featured on TechLogHub
[![Featured on TechLogHub](https://techloghub.com/badge-neutral.svg)](https://techloghub.com/open-source/googletest?utm_source=techloghub_badge&utm_medium=referral&utm_campaign=readme)

Find more projects like this

One email a week: new and trending developer tools, fresh comparisons, and what shipped. Unsubscribe in one click.