C++
ASSERT vs EXPECT
Learn the ASSERT_ and EXPECT_ macros.
The ASSERT and EXPECT difference
GoogleTest has two assertion families. EXPECT_ macros let the test continue on failure; ASSERT_ macros stop the test immediately. Both offer the same checks (EQ, TRUE, FALSE and so on).
The guidance is: when a precondition must hold or the rest is meaningless use ASSERT_; otherwise prefer EXPECT_. Example: ASSERT_NE(ptr, nullptr) checks a pointer is not null; if it is null the next lines crash, so the test stops. EXPECT_EQ(result, 42) is just a value check; on failure the test continues and reports other checks too.
Common assertion macros
Both families offer the same check types. EQ for equality, NE for inequality, TRUE for truth, FALSE for falsity, LT/LE/GT/GE for ordering (<, <=, >, >=). For strings use STREQ and STRNE.
Example: ASSERT_GE(score, 0) checks score is not negative and stops the test if it is. EXPECT_LT(price, maxPrice) checks the price is below the ceiling and continues even on failure. Which family you choose depends on whether the next lines still make sense.
Exercise Use ASSERT and EXPECT
Define a divide(int a, int b) function that returns 0 when b == 0. Inside TEST(DivTest, NonZero) first call ASSERT_TRUE(b != 0) as a precondition, then EXPECT_EQ(divide(10, 2), 5). In main print std::cout << "test: ready";.
Show example solution
#include <iostream>
#include <gtest/gtest.h>
int divide(int a, int b) {
if (b == 0) return 0;
return a / b;
}
TEST(DivTest, NonZero) {
int b = 2;
ASSERT_TRUE(b != 0);
EXPECT_EQ(divide(10, 2), 5);
}
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}
Test yourself
-
What happens when ASSERT_EQ fails?
- The test is skipped
- Only a warning is given
- The test stops immediately
- The next test is waited for
Show answer
The test stops immediately — On ASSERT_ failure the test stops immediately; the next lines do not run.
-
Match the macro to its behavior
- EXPECT_EQ
- Continues on failure
- ASSERT_EQ
- Stops on failure
- ASSERT_NE
- Passes if not equal
- EXPECT_TRUE
- Passes if true
-
Complete the precondition macro
ASSERT_TRUE(ready);
EXPECT_EQ(value, ____);
Show answer
ASSERT_TRUE(ready);
EXPECT_EQ(value, 42);
Next lesson: Test fixtures