skip to content

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%

answer

  1. what the macro expands to
  2. a bare return statement
  3. leaves the helper, not the test
  4. propagate, check, or return a result

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.

solid answer

~40 s

`ASSERT_*` and `FAIL()` expand to `return <expression of type void>`, so they compile only in `void` functions; in a `bool` helper clang reports that it cannot initialize a `bool` return object from `GoogleTest_NotSupported_OnFunctionReturningNonVoid` (aka `void`), and constructors and destructors reject them too. In a `void` helper the macro compiles, but on failure it returns from the **helper only**; the test body carries on, possibly into a null dereference. Three fixes: wrap the call in `ASSERT_NO_FATAL_FAILURE(Helper())`, test `if (HasFatalFailure()) return;` after it, or make the helper return `testing::AssertionResult` and write `ASSERT_TRUE(IsValidMonth(d))`, which also gives a good message. `SCOPED_TRACE` adds the call site to failures inside a shared helper.

code

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

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

void CheckMonth(const Date& d) {  // must return void to hold ASSERT_*
  ASSERT_GE(d.month, 1);
  ASSERT_LE(d.month, 12);  // on failure: returns from CheckMonth only
}

testing::AssertionResult IsValidMonth(const Date& d) {
  if (d.month >= 1 && d.month <= 12) return testing::AssertionSuccess();
  return testing::AssertionFailure() << "month " << d.month << " not in 1..12";
}

TEST(HelperTest, FatalFailureStaysInHelper) {
  CheckMonth(Date{2026, 13, 1});
  std::puts("still running after the helper failed");
}

TEST(HelperTest, PropagatedWithNoFatalFailure) {
  ASSERT_NO_FATAL_FAILURE(CheckMonth(Date{2026, 13, 1}));
  std::puts("not printed");
}

TEST(HelperTest, PredicateReturnsAssertionResult) {
  ASSERT_TRUE(IsValidMonth(Date{2026, 13, 1}));
  std::puts("not printed either");
}

go deeper

for a junior

Recall that ASSERT_* and FAIL() only work in functions returning void.

for a middle

Explain the expansion to a return statement and why it leaves only the current function.

for a senior

Diagnose a test that crashes after a helper's fatal failure and fix it with ASSERT_NO_FATAL_FAILURE, HasFatalFailure or an AssertionResult helper, adding SCOPED_TRACE for call sites.

for a principal

Choose a team pattern for shared test helpers, AssertionResult predicates or matchers, so failures propagate and read well without every author rediscovering this trap.

## What a fatal assertion expands to By default GoogleTest does not use exceptions to implement its assertions. A fatal assertion such as `ASSERT_GE(d.month, 1)` or `FAIL()` expands to an `if`/`else` whose failure branch is a **`return` statement**: ```cpp // simplified expansion of ASSERT_GE(d.month, 1) if (const AssertionResult r = CmpHelperGE(...)) ; else return AssertHelper(kFatalFailure, __FILE__, __LINE__, msg) = Message(); ``` The assignment `AssertHelper(...) = Message()` yields `void` in GoogleTest 1.18, through a type alias named `GoogleTest_NotSupported_OnFunctionReturningNonVoid`. A `return` with a `void` operand is legal only in a function whose return type is `void`. That single design choice explains both behaviours in the question. ## Why it does not compile in a non-void function In `bool CheckMonth(const Date& d)`, the expansion tries to return a `void` value from a function that must return `bool`. Apple clang 21 with GoogleTest 1.18 reports: `error: cannot initialize return object of type 'bool' with an rvalue of type 'GoogleTest_NotSupported_OnFunctionReturningNonVoid' (aka 'void')` The alias name is there to tell you what went wrong. The same rule bans fatal assertions in **constructors and destructors**, which are not `void`-returning functions in the language's sense; clang rejects one in a fixture constructor with "constructor ... must not return void expression". Non-fatal `EXPECT_*` and `ADD_FAILURE()` contain no `return`, so they work anywhere. ## Why it does not end the test from a void helper In `void CheckMonth(const Date& d)`, the macro compiles and, on failure, records a fatal failure and **returns from `CheckMonth`**. Control goes back to the test body, which knows nothing about it and continues. The GoogleTest guide shows the classic consequence: the next lines dereference a null pointer the helper was meant to rule out. That is undefined behaviour; in the guide's example it segfaults, which ends the whole test binary, so the remaining tests never report. ## Four ways to propagate the failure 1. **`ASSERT_NO_FATAL_FAILURE(statement)`** runs the statement and adds its own fatal failure if the statement produced a new one **in the current thread**, so the test body returns too. `EXPECT_NO_FATAL_FAILURE` records a non-fatal failure instead. 2. **`HasFatalFailure()`**, a static member of `testing::Test`, returns `true` once the current test has a fatal failure: `CheckMonth(d); if (HasFatalFailure()) return;`. Outside a test body, write `testing::Test::HasFatalFailure()`. `HasNonfatalFailure()` and `HasFailure()` exist too. 3. **Return a `testing::AssertionResult`.** A helper returning `AssertionSuccess()` or `AssertionFailure() << "month 13 not in 1..12"` composes with `ASSERT_TRUE(IsValidMonth(d))` and `EXPECT_TRUE(...)`, so the **caller** chooses fatal or non-fatal and the explanation appears in the failure output. 4. **Turn fatal failures into exceptions.** A `testing::EmptyTestEventListener` whose `OnTestPartResult` throws `testing::AssertionException` on a fatal failure makes `ASSERT_*` unwind through any depth of helpers. It needs exceptions enabled and is usually registered in your own `main()`. An out parameter is the documented workaround when a helper must produce a value: rewrite `Date Parse(...)` as `void Parse(..., Date* out)` and make sure `*out` holds something sensible on an early return. ## Telling call sites apart A helper called from many places produces failures that all point at the same line inside the helper, so the report says what failed but not for which input. `SCOPED_TRACE(message)` adds the current file, line and message to every failure raised while it is in scope, and the effect ends when control leaves that lexical scope. Practical habits: - Put one `SCOPED_TRACE` at the top of the helper with the input in the message, instead of one at every call site. - In a loop over inputs, include the loop variable or the input string in the message, so the failing iteration is named. - Nested traces are all printed, innermost first, so a helper that calls another helper keeps both contexts. - `testing::ScopedTrace` takes an explicit file and line, which suits a reusable helper library that wants to point at its caller. ## A decision table | Need | Use | |---|---| | Helper must stop the test when it fails | `void` helper plus `ASSERT_NO_FATAL_FAILURE` at the call | | Helper is a reusable predicate | return `testing::AssertionResult` | | Many sequential helper calls | `HasFatalFailure()` checks, or an exception-throwing listener | | Several call sites | `SCOPED_TRACE` with the input | For checks used across many tests, the GoogleTest guide also suggests a custom gMock matcher, which is covered with the mocking material.

  • Does ASSERT_NO_FATAL_FAILURE see failures raised in threads the statement starts?
    No. It checks only for new fatal failures in the thread that runs the assertion; failures in threads the statement creates are ignored. A helper that fans work out to threads has to collect results and assert on them in the calling thread.
  • Why is a fatal assertion in a void helper called from a fixture constructor especially dangerous?
    The constructor itself cannot hold `ASSERT_*`, so people move the check into a private `void` helper. On failure that helper returns early into the constructor, which carries on and may leave the object partly constructed while the test runs anyway. Put such checks in `SetUp()` instead, or abort.

  • ASSERT_* in a helper ends the whole test, like an exception would.
  • ASSERT_* works in any function; only the message changes.
  • Fatal assertions are fine inside a fixture's constructor.
  • HasFatalFailure() also reports failures from earlier, already finished tests.
  • ASSERT_NO_FATAL_FAILURE catches failures from threads the statement starts.

Assumes GoogleTest 1.18; the void type alias named in clang's diagnostic is that release's spelling.