Assertions
A test assertion checks that a condition holds and records a failure if it does not. GoogleTest uses EXPECT_* / ASSERT_*. Catch2 uses CHECK / REQUIRE. <cassert> assert is a debug runtime check, not a test reporter.
Detailed Explanation
Production assert(cond) from <cassert> aborts the process when NDEBUG is unset and does nothing when it is set. It is a programmer error detector, not a unit-test result. Tests that only assert will look like a crash in CI and disappear in release test builds.
A test assertion reports file, line, expected, actual, and continues the suite. That is the job of the framework macros.
GoogleTest: EXPECT_EQ(a, b) compares with == and prints both values if they can be streamed. EXPECT_STREQ is for const char*, because EXPECT_EQ on two C strings compares pointers. EXPECT_NEAR(a, b, eps) is for floats. EXPECT_THROW(stmt, Ex) runs stmt and requires that exception type. ASSERT_* is the same check but returns from the current function on failure.
Catch2: REQUIRE(a == b) decomposes the expression and prints a and b. You write C++ in the parens. REQUIRE_THAT(s, StartsWith("http")) uses matchers.
What to assert: the observable contract, not the private layout. Prefer one idea per assertion so the first failure is readable. Prefer comparing values you would print in a log (status == 404) over comparing entire blobs unless you have a golden file on purpose.
Floating point: do not EXPECT_EQ on double after arithmetic. Use an epsilon, or compare in a known unit (integer cents).
Death versus throw: EXPECT_THROW is for C++ exceptions. EXPECT_DEATH is for abort / exit / a signal (GoogleTest death tests). assert failures are death, not std::exception.
Custom types need operator== and, for readable failures, operator<<. GoogleTest can use EXPECT_TRUE(a == b) if you do not want to stream.
Do not assert from a destructor or from a worker thread GoogleTest does not know about; the result may not be recorded. Join threads in the test body, then assert.
Code Examples
#include <gtest/gtest.h>
#include <stdexcept>
#include <string>
int parsePort(const std::string& s) {
if (s.empty()) throw std::invalid_argument("empty");
return 8080;
}
TEST(Parse, Port) {
EXPECT_EQ(parsePort("x"), 8080);
EXPECT_THROW(parsePort(""), std::invalid_argument);
}#include <cassert>
#include <cmath>
double hypot2(double x, double y) { return std::sqrt(x * x + y * y); }
int main() {
assert(hypot2(3, 4) > 4.9); // debug-only; not a test report
}Common Gotchas
`EXPECT_EQ(cstr1, cstr2)`
pointer equality. Use `STREQ` or `std::string`.
`assert` in tests under `NDEBUG`
the check vanishes. Use the framework.
`ASSERT` in a helper in GoogleTest
returns from the helper only. Return a `bool` or use `EXPECT`.
Float `EQ` is almost always wrong
prefer `NEAR` or integer units.