skip to content

GoogleTest

The C++ testing framework with its assertion macros, fixtures, parameterized and typed tests, and the GoogleMock companion. Interviewers ask because it is the default choice for testing native code.

on this pageshow

explore

questions

21

In GoogleTest, what is the difference between ASSERT_EQ and EXPECT_EQ, and when should a test use each?

level: juniorimportance: must knowfreq 78%

answer

  1. fatal versus non-fatal
  2. what runs on the next line
  3. the current function, not the program
  4. a guard before reading a value

basics

~20 s

EXPECT_EQ records a non-fatal failure and the function keeps running, so one run reports every mismatch. ASSERT_EQ records a fatal failure and returns from the current function; use it when the following lines depend on the check.

solid answer

~40 s

Both macros compare two values with `==`, print both values on failure and mark the test failed; the difference is control flow. `EXPECT_EQ` produces a **non-fatal** failure: execution continues, so a test that checks the year, month and day of a parsed date reports every wrong field in one run. `ASSERT_EQ` produces a **fatal** failure and returns from the **current function**, which is the test body or the helper it sits in. Use `EXPECT_*` by default and `ASSERT_*` as a guard where carrying on is pointless or would crash: an `std::optional` that must hold a value, a size checked before indexing, a file that must have opened. Every assertion accepts a streamed message, as in `ASSERT_TRUE(d.has_value()) << "input: " << text;`, and the framework builds it only when the check fails.

code

cpp · 25 lines
cpp
#include <gtest/gtest.h>
#include <cstdio>
#include <optional>

struct Date { int year, month, day; };

std::optional<Date> ParseDate(const char* text) {
  Date d{};
  if (std::sscanf(text, "%4d-%2d-%2d", &d.year, &d.month, &d.day) != 3)
    return std::nullopt;
  return d;
}

TEST(ParseDateTest, ParsesIsoDate) {
  const char* input = "2026-10-26";
  std::optional<Date> d = ParseDate(input);
  ASSERT_TRUE(d.has_value()) << "could not parse " << input;  // guard
  EXPECT_EQ(d->year, 2026);  // non-fatal: every wrong field is reported
  EXPECT_EQ(d->month, 10);
  EXPECT_EQ(d->day, 26);
}

TEST(ParseDateTest, RejectsSlashes) {
  EXPECT_FALSE(ParseDate("26/10/2026").has_value());
}

go deeper

for a junior

Recall the pairing: EXPECT continues after a failure, ASSERT returns from the current function. Both fail the test.

for a middle

Explain that fatal means a return from the current function, not a process abort, and show where a guard ASSERT prevents undefined behaviour on the next line.

for a senior

Show the policy you apply in review: EXPECT by default, ASSERT only before code that cannot run safely, and streamed context that names the input.

for a principal

Frame the trade-off as diagnostic yield per run against cascading noise, and how a team convention keeps failure reports readable in CI.

## Two families with one comparison GoogleTest, the C++ testing framework, defines most of its checks twice. `EXPECT_EQ(a, b)` and `ASSERT_EQ(a, b)` both verify `a == b`; the same pairing exists for `_NE`, `_LT`, `_LE`, `_GT`, `_GE`, `_TRUE`, `_FALSE`, `_STREQ`, `_DOUBLE_EQ`, `_NEAR`, `_THROW` and the death assertions. On failure both print the two expressions and their values, both record the failure against the running test, and both make the test fail. The comparison is identical; what differs is what happens to the **next line**. - **`EXPECT_*`** generates a **non-fatal failure**. The current function keeps running. - **`ASSERT_*`** generates a **fatal failure** and **returns from the current function** at once. A test is reported as failed if any assertion in it failed, fatal or not. A non-fatal failure is not a warning. ## What "fatal" actually means "Fatal" is narrower than it sounds. By default a failed `ASSERT_EQ` does not abort the process, does not throw an exception and does not stop the other tests in the binary. (The `--gtest_throw_on_failure` flag changes that, for running GoogleTest assertions under another framework; ordinary test binaries leave it off.) The macro expands to a `return` statement, so it leaves only the function it appears in. In a `TEST` body that ends the test; the framework records the failure and moves on to the next test. Inside a helper function it ends only the helper, a trap covered with assertions in helper functions. The framework also evaluates each argument **exactly once**, so `EXPECT_EQ(Next(), 3)` is safe even though `Next()` has a side effect, but the order in which the two arguments are evaluated is unspecified. ## How a failure is reported A failed comparison prints the source location, both expressions and the values they produced, for example `Expected equality of these values:` followed by `d.year` with `Which is: 2026` and then `2025`. That is why the comparison macros beat a bare Boolean check: - `EXPECT_EQ(d.year, 2026)` prints both values, so the failure explains itself. - `EXPECT_TRUE(d.year == 2026)` can only report that the expression was `false`; the actual year is lost. - The relational macros `EXPECT_LT`, `EXPECT_LE`, `EXPECT_GT` and `EXPECT_GE` print both operands in the same way. At the end of the run each failed test is listed, and the program's exit status is nonzero when any test failed, which is what a CI job checks. ## Choosing between them The usual rule is: **`EXPECT_*` by default, `ASSERT_*` as a guard**. | Situation | Use | Why | |---|---|---| | Comparing several independent fields | `EXPECT_*` | one run shows every wrong field | | An `std::optional` or pointer about to be read | `ASSERT_*` | reading an empty optional or a null pointer is undefined behaviour | | A container size checked before indexing | `ASSERT_*` | an out-of-range index would crash or corrupt | | A resource the rest of the test needs | `ASSERT_*` | later failures would be noise | Using `ASSERT_*` everywhere hides information: the first wrong field stops the test, so you fix one bug per run. Using `EXPECT_*` everywhere is dangerous in the other direction: after a failed `EXPECT_TRUE(d.has_value())` the next line still calls `d->year`, which is undefined behaviour and may crash the whole test binary, so the remaining tests never report at all. ## Streaming a message Every assertion accepts extra context with `<<`, exactly like an `std::ostream`: ```cpp ASSERT_TRUE(d.has_value()) << "could not parse " << input; EXPECT_EQ(d->day, 26) << "day field of " << input; ``` The message is appended to the failure output. The macro expands to an `if`/`else` whose failure branch holds the stream, so the streamed operands are evaluated **only when the check fails**; an expensive `Describe(input)` call costs nothing on a passing run. ## A worked example For a date parser returning `std::optional<Date>`, one guard and three non-fatal checks give the most information per run: 1. `ASSERT_TRUE(d.has_value())` stops the test if parsing failed, because nothing below can run safely. 2. `EXPECT_EQ(d->year, 2026)`, `EXPECT_EQ(d->month, 10)` and `EXPECT_EQ(d->day, 26)` each report independently. 3. If the parser swaps month and day, the run shows both wrong fields together, which points straight at the swap. ## Common mistakes - Believing a failed `EXPECT_*` lets the test pass; it fails the test and only lets execution continue. - Believing `ASSERT_*` stops the whole program; only the current function returns. - Putting `ASSERT_*` in a function that returns a value, which does not compile, or in a `void` helper while expecting it to end the test, which it does not. - Writing `EXPECT_EQ(ptr, NULL)`; the reference asks for `EXPECT_EQ(ptr, nullptr)`. - Comparing C strings or floating-point values with `EXPECT_EQ`, which compares pointers or exact bits rather than what you meant.

  • Does a failed ASSERT_* stop the remaining tests in the binary?
    No. It returns from the current function, the framework marks that test failed and runs the next test as usual. Stopping the whole run at the first failing test is a runner option, `--gtest_fail_fast` or the `GTEST_FAIL_FAST` environment variable, not something an assertion does.
  • When control flow rather than a value decides the outcome, which GoogleTest macros do you use?
    `FAIL()` generates a fatal failure and returns from the current function, so it has the same `void`-only restriction as `ASSERT_*`. `ADD_FAILURE()` generates a non-fatal failure and continues. Both take a streamed message, which suits a `default:` branch of a `switch` that should be unreachable. `SUCCEED()` exists but is documentary and does not make a test pass.

A pre-flight checklist: a scratched seat is noted and the check continues (EXPECT), but a missing wing ends this inspection on the spot (ASSERT), because inspecting the rest is pointless. The next aircraft still gets its own inspection.

  • A failed EXPECT_* is only a warning and the test still passes.
  • ASSERT_* aborts the whole test program on failure.
  • Use ASSERT_* everywhere so the first failure is the only one to read.
  • EXPECT_EQ evaluates its arguments twice, once to compare and once to print.
  • A streamed failure message is built on every run, so keep it cheap.
open as a page

In GoogleTest, how does TEST_F differ from TEST, and does each TEST_F get its own fixture object?

level: juniorimportance: must knowfreq 70%

basics

~20 s

TEST_F's first argument is a fixture class derived from testing::Test, and the test body can use its members. GoogleTest builds a fresh fixture object for every TEST_F and destroys it afterwards, so nothing stored in its members carries over.

open as a page

What does linking GoogleTest's gtest_main library give a test binary, and what must a hand-written main() do instead?

level: juniorimportance: must knowfreq 70%

basics

~20 s

gtest_main supplies a main() that calls testing::InitGoogleTest(&argc, argv) and returns RUN_ALL_TESTS(). A hand-written main must do the same: initialise first so --gtest_* flags are parsed, then return RUN_ALL_TESTS()'s result so failures reach the exit code.

open as a page

In GoogleTest, how do TEST_P and INSTANTIATE_TEST_SUITE_P run one test body over many values, and how are the generated tests named?

level: middleimportance: must knowfreq 55%

basics

~20 s

A fixture derived from testing::TestWithParam<T> holds the TEST_P bodies, which read GetParam(). INSTANTIATE_TEST_SUITE_P supplies values from a generator such as Values or Combine, and each value becomes a test named Prefix/Suite.Test/index unless a name generator supplies the suffix.

open as a page

In GoogleMock, how do you declare a mock method with MOCK_METHOD and set an expectation on it with EXPECT_CALL?

level: middleimportance: must knowfreq 70%

basics

~20 s

MOCK_METHOD(ReturnType, Name, (Args...), (Specs...)) in a public section generates the mock member. EXPECT_CALL(mock, Name(matchers...)) then states, before the code runs, which calls must happen, how often, and what they return; unmet expectations fail when the mock is destroyed.

open as a page

In GoogleMock, what is the difference between ON_CALL and EXPECT_CALL, and when should a test use each?

level: middleimportance: must knowfreq 65%

basics

~20 s

ON_CALL sets a mock method's default behaviour and verifies nothing. EXPECT_CALL adds a constraint: the call must happen, with matching arguments, the stated number of times. Stub with ON_CALL; use EXPECT_CALL only for calls the test verifies.

open as a page

How does GoogleTest's --gtest_filter flag select tests, including negative patterns and the names of parameterized tests?

level: middleimportance: must knowfreq 65%

basics

~20 s

--gtest_filter takes colon-separated wildcard patterns matched against full names like Suite.Test; an optional dash introduces patterns to exclude. * and ? are the only wildcards. Parameterized tests carry their prefix and index, as in Small/Sizes.Fits/0.

open as a page

In GoogleTest, what exactly does EXPECT_THROW check, and how do you also verify the exception's message?

level: middleimportance: should knowfreq 52%

basics

~20 s

EXPECT_THROW(statement, Type) runs the statement and passes if it throws something a catch (Type const&) handler catches, so derived types pass too. It never looks at what(); check the message with ThrowsMessage or a try/catch.

open as a page

In GoogleTest, why can EXPECT_EQ give the wrong verdict for C strings and doubles, and which assertions should replace it?

level: middleimportance: should knowfreq 58%

basics

~10 s

EXPECT_EQ uses ==, which compares addresses for C strings and exact bits for doubles. Use EXPECT_STREQ for C strings and EXPECT_DOUBLE_EQ, EXPECT_FLOAT_EQ or EXPECT_NEAR for floating-point values.

open as a page

In a GoogleTest fixture, when should set-up and clean-up go in SetUp and TearDown rather than the constructor and destructor?

level: middleimportance: should knowfreq 50%

basics

~10 s

Prefer the constructor and destructor for plain initialisation, which allows const members and guaranteed base-first order. Use SetUp for set-up that needs ASSERT_* or calls virtual functions, and TearDown for clean-up that may throw.

open as a page

In GoogleTest, how do typed tests differ from type-parameterized tests, and why must a typed test body use this-> for fixture members?

level: middleimportance: should knowfreq 35%

basics

~20 s

Typed tests fix the type list where the suite is written with TYPED_TEST_SUITE; type-parameterized tests define patterns first and are instantiated later, possibly elsewhere. The body is a member of a class template derived from the fixture, so its members need this->.

open as a page

How do you make a GoogleTest binary write a JUnit-style XML report, and what does the report hold after a --gtest_repeat run?

level: middleimportance: should knowfreq 50%

basics

~20 s

Pass --gtest_output=xml:path (or set GTEST_OUTPUT); plain xml writes test_detail.xml, and a path ending in / names a directory where the file is named after the binary. With --gtest_repeat the file is rewritten after every iteration, so it shows only the last one.

open as a page

Why does GoogleTest's ASSERT_GE fail to compile in a helper returning bool, and why does it not end the test from a void helper?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A fatal assertion expands to a return statement with a void value, so it compiles only in functions returning void. In a void helper that return leaves only the helper, and the test continues unless the caller checks for the fatal failure.

open as a page

In GoogleTest, how does EXPECT_DEATH decide a statement died, and when should you switch the death test style to threadsafe?

level: seniorimportance: should knowfreq 40%

basics

~20 s

EXPECT_DEATH runs the statement in a child process and passes if the child exits with a nonzero status or is killed, and its stderr matches the regex. Switch from the default fast style to threadsafe when threads exist at the death test.

open as a page

In GoogleTest, when is SetUpTestSuite worth using over per-test SetUp, and what goes wrong when tests share the resource it creates?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Use static SetUpTestSuite and TearDownTestSuite when a resource is expensive and the tests only read it. Tests that modify it become order-dependent, and failures appear or vanish under filtering and shuffling.

open as a page

When two GoogleMock EXPECT_CALLs on one method both match a call, which one wins, and how do InSequence and RetiresOnSaturation change that?

level: seniorimportance: should knowfreq 45%

basics

~20 s

GoogleMock searches expectations in reverse declaration order and uses the newest active one that matches, even if it is saturated. RetiresOnSaturation lets a full expectation step aside; InSequence makes expectations match only in the order declared.

open as a page

A GoogleMock test warns "Uninteresting mock function call" for one method and fails with "Unexpected mock function call" for another. What separates the two, and how do NiceMock, NaggyMock and StrictMock change each?

level: seniorimportance: should knowfreq 55%

basics

~20 s

An uninteresting call hits a method with no EXPECT_CALL; an unexpected call hits a method that has EXPECT_CALLs, none of which match. Unexpected calls always fail. NiceMock silences uninteresting calls, NaggyMock (the default) warns, StrictMock fails them.

open as a page

In CMake's GoogleTest module, how do gtest_discover_tests and gtest_add_tests differ, and when does each one find the tests?

level: seniorimportance: should knowfreq 45%

basics

~20 s

gtest_add_tests finds tests at configure time by scanning sources with a regular expression, so a parameterized test stays one wildcard entry. gtest_discover_tests runs the built binary with --gtest_list_tests after the build or before testing, registering every instantiation.

open as a page

A CI job must run a flaky GoogleTest subset 100 times in random order. Which flags do that, and how do you replay the exact order of a failing iteration?

level: seniorimportance: should knowfreq 50%

basics

~10 s

Run with --gtest_filter=<subset> --gtest_repeat=100 --gtest_shuffle. Each iteration prints its seed, and the seed rises by one per iteration. Replay a failure with the same filter, --gtest_shuffle and --gtest_random_seed set to that iteration's printed seed.

open as a page

As a lead, what GoogleMock policy would you set for a codebase on nice versus strict mocks, ON_CALL versus EXPECT_CALL, and which types tests may mock?

level: principalimportance: should knowfreq 35%

basics

~20 s

Default to NiceMock or naggy mocks and keep StrictMock for protocols where any extra call is a bug; stub with ON_CALL and use EXPECT_CALL only for the interaction under test; mock only interfaces the team owns, through adaptors, with one shared mock per interface.

open as a page

In GoogleMock, how do you mock a dependency whose member functions are not virtual, and what must change in the code under test?

level: seniorimportance: nice to knowfreq 35%

basics

~20 s

Write a mock class unrelated to the real one, with MOCK_METHOD members of the same signatures and no override, and make the code under test a template on the dependency type. Production instantiates it with the real class, tests with the mock.

open as a page