In GoogleTest, how does EXPECT_DEATH decide a statement died, and when should you switch the death test style to threadsafe?
answer
- a child process runs the statement
- nonzero exit plus stderr match
- fork with threads alive
- re-execute the binary instead
basics
~20 sEXPECT_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.
solid answer
~40 sA death assertion spawns a **child process**: on POSIX it forks (using `clone()` on Linux), on Windows it uses `CreateProcess()`. `EXPECT_DEATH(statement, regex)` passes when the child **terminates with a nonzero exit status or by a signal** and its **stderr** matches the regex, which is a substring search, not a full match. `exit(0)`, returning, or throwing all count as not dying. `EXPECT_EXIT` takes a predicate such as `ExitedWithCode(2)` or `KilledBySignal(SIGSEGV)`. In GoogleTest 1.18 the default `death_test_style` is **"fast"**: the forked child runs the statement directly. Forking a multithreaded process copies only the calling thread, so a lock held elsewhere can hang the child; GoogleTest warns when it detects several threads. **"threadsafe"** makes the child re-execute the test binary to run just that death test, slower but safe. Set it with `--gtest_death_test_style=threadsafe` or `GTEST_FLAG_SET(death_test_style, "threadsafe")`.
code
cpp · 28 lines#include <gtest/gtest.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
int DaysInMonth(int month) {
assert(month >= 1 && month <= 12 && "month out of range");
if (month < 1 || month > 12) return 0; // what a release build reaches
static const int kDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return kDays[month - 1];
}
[[noreturn]] void RejectDate(const char* text) {
std::fprintf(stderr, "unparseable date: %s\n", text);
std::exit(2);
}
TEST(DateDeathTest, AssertFiresOnMonth13) {
EXPECT_DEATH(DaysInMonth(13), "month out of range");
}
TEST(DateDeathTest, DebugOnlyCheck) {
EXPECT_DEBUG_DEATH(DaysInMonth(13), "month out of range");
}
TEST(DateDeathTest, ExitsWithCode2) {
EXPECT_EXIT(RejectDate("31/02"), testing::ExitedWithCode(2), "unparseable");
}go deeper
Recall that a death test checks that code terminates the process, and that EXPECT_DEATH takes a statement and an stderr pattern.
Explain the child process, what counts as dying, the substring regex match, and EXPECT_EXIT with ExitedWithCode or KilledBySignal.
Diagnose a hanging death test caused by threads alive at fork time and fix it with the threadsafe style or DeathTest ordering; catch the NDEBUG release-build failure.
Weigh death tests' cost and flakiness against testing contracts through exceptions or error codes, and decide where crashing on a broken precondition is the right contract.
## What a death test is for Some code is meant to stop the process: an `assert` on a broken precondition, a check that calls `std::abort()`, a fatal error path that calls `std::exit(2)`. A **death test** verifies that this happens, and with the right message. A thrown exception is not death in GoogleTest's sense, because a caller could catch it; exceptions are tested with `EXPECT_THROW`. ## How the verdict is reached GoogleTest runs the statement in a **child process**, so the test program itself survives: - On POSIX systems the child is created with `fork()`, or `clone()` on Linux. - On Windows it is created with `CreateProcess()` and re-executes the test binary. The parent then waits and judges the child: 1. **Did it die?** For `EXPECT_DEATH` and `ASSERT_DEATH`, the child must exit with a **nonzero** status or be killed by a signal. `std::exit(0)` fails the death test with "died but not with expected exit code". A statement that runs to completion fails with "failed to die". 2. **For `EXPECT_EXIT`**, the exit status must satisfy a predicate: `testing::ExitedWithCode(n)` or, outside Windows, `testing::KilledBySignal(sig)`. 3. **Does stderr match?** The second argument is a matcher for `const std::string&` or a regular expression; a bare string is treated as `ContainsRegex(s)`, so it searches for a match anywhere in stderr. With a POSIX build outside Bazel, the syntax is POSIX extended regular expressions; on Windows it is GoogleTest's own simple regex, which lacks alternation and grouping. Because the statement runs in another process, **side effects are invisible** to the parent: a variable it changes or memory it frees stays unchanged in the test. A statement that leaves via `return` or an exception also fails the death test, so `ASSERT_*` inside the statement is reported as "illegal return in test statement". ## Fast versus threadsafe The `death_test_style` flag picks how the POSIX child starts: | Style | Child does | Cost | Risk | |---|---|---|---| | `"fast"` (default in 1.18) | runs the statement right after `fork()` | cheap | can hang if other threads existed | | `"threadsafe"` | re-executes the binary to run only this death test | a full process start per death test | far lower | The risk comes from `fork()` semantics: the child contains a copy of only the **calling thread**. A mutex another thread held at the moment of the fork stays locked forever in the child, so a statement that allocates memory or writes a log can deadlock. GoogleTest raises awareness three ways: 1. It prints a warning when it detects multiple threads at a death test. On macOS the 1.18 text begins: `Death tests use fork(), which is unsafe particularly in a threaded context. For this test, Google Test detected 2 threads.` 2. It runs test suites whose names end in **`DeathTest`** before all other tests, so they fork before later tests have started threads. Name the suite `DateDeathTest`, or alias a shared fixture as `using DateDeathTest = DateTest;`. 3. On Linux it uses `clone()` instead of `fork()`. Switch to `"threadsafe"` when threads already exist at that point and cannot be avoided, for example a library that starts a thread pool from a static initializer. Set it for the binary with `--gtest_death_test_style=threadsafe` or in `main()`, or for one test with `GTEST_FLAG_SET(death_test_style, "threadsafe");`, since flags are saved and restored around each test. Threads created **inside** the statement are harmless. Even threadsafe mode can deadlock through handlers registered with `pthread_atfork`. ## The release-build trap A death test aimed at `assert` passes in a debug build and fails in a release build with "failed to die", because `NDEBUG` compiles `assert` out. Two fixes: - `EXPECT_DEBUG_DEATH(statement, regex)` behaves like `EXPECT_DEATH` without `NDEBUG` and simply runs the statement with it, so the code must be safe to run in release builds. - Keep a check that does not depend on `NDEBUG` when the crash is part of the contract. ## Other rules worth knowing - Prefer `EXPECT_EXIT` with `ExitedWithCode(n)` when the exit code is part of the contract, since `EXPECT_DEATH` accepts any nonzero status. - Keep the regex specific to the message your code prints; an empty pattern accepts any crash, including an unrelated one. - Two death assertions cannot share one source line; compilation fails with an unhelpful error. - `EXPECT_DEATH_IF_SUPPORTED` verifies nothing on platforms without death-test support. - With mocks and a specific exit code, the mock leak detector can change the exit status unless the mock is allowed to leak.
- Why does GoogleTest run test suites named *DeathTest first?So their forks happen before other tests have had a chance to start threads, which makes the default fast style safer. The rule matches on the suite name, so a fixture shared with ordinary tests is usually aliased, as in `using DateDeathTest = DateTest;`, and the death tests use the alias.
- Why can't a death test observe that the statement released memory or changed a variable?The statement runs in a separate child process, so every in-memory side effect happens in the child's copy of the address space and vanishes with it. Only the exit status and the child's stderr come back to the parent.
- EXPECT_DEATH passes if the statement throws an exception.
- A child that calls exit(0) counts as having died.
- The regex must match the whole of stderr, not just part of it.
- The threadsafe style is the default in GoogleTest.
- Creating threads inside the death test statement makes fast mode unsafe.
- Variables changed in the death test statement are visible afterwards in the test.
Assumes GoogleTest 1.18; its default death_test_style is "fast" and the quoted warning is that release's text.