C++
TEST macro
Learn to write tests with the TEST macro.
TEST macro syntax
The TEST macro takes two arguments: a test suite name and a test name. Both must be valid C++ identifiers (letters, digits, underscores; not starting with a digit). The test body goes between the braces.
Example: TEST(CalcTest, Adds) { ... }. Here CalcTest is a group and Adds is a test in it. Tests sharing a suite name appear together in the output. This lets you group related tests under one umbrella. The suite name is usually the class name and the test name is the behavior.
Assertions in the test body
Inside the test body you call assertion macros to check expected behavior. The most common are: EXPECT_EQ(a, b) for equality, EXPECT_TRUE(x) for truth, EXPECT_FALSE(x) for falsity, EXPECT_STREQ(s1, s2) for string equality.
A test can have many assertions; they all run in order. Example: TEST(CalcTest, Adds) { EXPECT_EQ(add(2, 3), 5); EXPECT_EQ(add(0, 0), 0); }. Even if the first assertion fails the second still runs (an EXPECT feature). This makes checking many cases in one test easy.
Exercise Write the CalcTest test
Define an add(int a, int b) function (returns a + b). Inside TEST(CalcTest, Adds) call EXPECT_EQ(add(2, 3), 5) and EXPECT_EQ(add(0, 0), 0). In main print std::cout << "test: ready";.
Show example solution
#include <iostream>
#include <gtest/gtest.h>
int add(int a, int b) { return a + b; }
TEST(CalcTest, Adds) {
EXPECT_EQ(add(2, 3), 5);
EXPECT_EQ(add(0, 0), 0);
}
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}
Test yourself
-
Complete the TEST macro
____(CalcTest, Adds) {
EXPECT_EQ(add(2, 3), 5);
}
Show answer
TEST(CalcTest, Adds) {
EXPECT_EQ(add(2, 3), 5);
}
-
What does the first argument of the TEST macro specify?
- The test duration
- The test file name
- The expected output
- The test suite name
Show answer
The test suite name — The first argument is the test suite name; it groups related tests.
-
Match the assertion macro to its role
- EXPECT_EQ(a, b)
- Checks equality
- EXPECT_TRUE(x)
- Checks truth
- EXPECT_FALSE(x)
- Checks falsity
- EXPECT_STREQ(s1, s2)
- Checks string equality
Next lesson: ASSERT vs EXPECT