ASSERT vs EXPECT
- C++ course
- Advanced
- Lesson 39/83
- 5 min
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.
Practice 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";.
Starter code
#include <iostream>
#include <gtest/gtest.h>
// Define the divide function
// Add the TEST(DivTest, NonZero) macro
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}Sample 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;
}Expected output
test: ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when ASSERT_EQ fails?
- The test is skipped
- Only a warning is given
- The test stops immediately Correct answer
- The next test is waited for
Explanation: On ASSERT_ failure the test stops immediately; the next lines do not run.
2 Match the macro to its behavior
| Term | Meaning |
|---|---|
EXPECT_EQ |
Continues on failure |
ASSERT_EQ |
Stops on failure |
ASSERT_NE |
Passes if not equal |
EXPECT_TRUE |
Passes if true |
3 Complete the precondition macro
ASSERT_TRUE(ready);
EXPECT_EQ(value, ____);
ASSERT_TRUE(ready);
EXPECT_EQ(value, 42);
Explanation: ASSERT_TRUE guards the precondition, EXPECT_EQ checks the value.