TEST macro
- C++ course
- Advanced
- Lesson 38/83
- 5 min
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.
Practice 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";.
Starter code
#include <iostream>
#include <gtest/gtest.h>
// Define the add function
// Add a test to the CalcTest suite
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}Sample 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;
}Expected output
test: ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the TEST macro
____(CalcTest, Adds) {
EXPECT_EQ(add(2, 3), 5);
}
TEST(CalcTest, Adds) {
EXPECT_EQ(add(2, 3), 5);
}
Explanation: The TEST macro defines a test.
2 What does the first argument of the TEST macro specify?
- The test duration
- The test file name
- The expected output
- The test suite name Correct answer
Explanation: The first argument is the test suite name; it groups related tests.
3 Match the assertion macro to its role
| Term | Meaning |
|---|---|
EXPECT_EQ(a, b) |
Checks equality |
EXPECT_TRUE(x) |
Checks truth |
EXPECT_FALSE(x) |
Checks falsity |
EXPECT_STREQ(s1, s2) |
Checks string equality |