skip to content

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.