Death tests
A death test checks that a statement aborts the process: abort, exit, an uncaught exception that calls terminate, or a signal. GoogleTest runs the statement in a child process and looks at the exit status and stderr.
Detailed Explanation
Some contracts are "this must not return". A CHECK macro in production code calls abort. A noexcept function that throws calls std::terminate. You cannot EXPECT_THROW those: there is no C++ exception at the test's level, or the process is already dead.
EXPECT_DEATH(stmt, regex) forks (or clones, depending on style) a child, runs stmt, and expects a non-zero death whose stderr matches regex. EXPECT_EXIT(stmt, predicate, regex) lets you check ExitedWithCode(n) or KilledBySignal(sig). ASSERT_DEATH is the aborting form.
Styles: "fast" (clone/fork, default on POSIX) is quick and shares memory copy-on-write. "threadsafe" re-execs the binary and is required if the parent is already multi-threaded (fork plus threads is unsafe). Set GTEST_FLAG_SET(death_test_style, "threadsafe") when you have threads.
Death tests must be named *DeathTest as the suite suffix if they share a binary with other tests, so GoogleTest runs them first (before other tests spawn threads). That is a convention the runner honours.
Do not death-test ordinary error handling. If the function throws std::invalid_argument, use EXPECT_THROW. Death tests are for "the process must die". They are slower and harder to debug (the failure is in a child).
Catch2 does not ship the same first-class death API. You write a small helper binary or skip those cases.
assert from <cassert> dies only when NDEBUG is unset. A death test of assert will fail in release. Test the production CHECK you actually ship.
Code Examples
#include <cstdlib>
#include <gtest/gtest.h>
[[noreturn]] void die() { std::abort(); }
TEST(AbortDeathTest, Aborts) {
EXPECT_DEATH(die(), ".*");
}#include <gtest/gtest.h>
#include <stdexcept>
void boom() { throw std::runtime_error("nope"); }
TEST(Throw, IsNotDeath) {
EXPECT_THROW(boom(), std::runtime_error);
}Common Gotchas
Fork plus threads
if any test already started a thread, fast death tests are unsafe. Use `threadsafe` style or isolate death tests in their own binary.
Suite name should end in `DeathTest`
otherwise they may run after threads exist.
Expecting death from a function that throws
`EXPECT_DEATH` will see an uncaught exception in the child (which may call `terminate` — that *is* death). Prefer `EXPECT_THROW` when you meant an exception.
Regex is on stderr
a silent `abort` still matches `".*"`. A too-tight regex flakes across libstdc++ message changes.