GoogleTest
- C++ course
- Advanced
- Lesson 37/83
- 5 min
Learn the GoogleTest test framework.
What is GoogleTest?
GoogleTest (gtest) is a popular test framework for C++. It is developed by Google and open source. It provides macros to write, run and report tests. It is the standard choice for C++20 projects.
To use it you add #include <gtest/gtest.h>. Each test is defined with a TEST macro. In main you call testing::InitGoogleTest and RUN_ALL_TESTS() to run all tests. In this lesson we learn the syntax; we keep the output simple with std::cout.
The TEST macro and assertions
In GoogleTest each test is written with the TEST(SuiteName, TestName) macro. Inside the braces are assertions: EXPECT_EQ(a, b) checks that a equals b, and EXPECT_TRUE(x) checks that x is true.
Multiple tests can share a suite name to group related tests. Example: TEST(CalcTest, Adds) { EXPECT_EQ(2 + 2, 4); }. Here CalcTest is the suite and Adds is the test name. On assertion failure the test either continues (EXPECT) or stops (ASSERT); we will see this distinction next.
Practice Write your first GoogleTest program
Add the #include <gtest/gtest.h> header. Inside TEST(SampleTest, Equals) call EXPECT_EQ(2 + 2, 4). In main print std::cout << "test: ready";.
Starter code
#include <iostream>
// Add the <gtest/gtest.h> header and TEST macro
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}Sample solution
#include <iostream>
#include <gtest/gtest.h>
TEST(SampleTest, Equals) {
EXPECT_EQ(2 + 2, 4);
}
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 Which header is included for GoogleTest?
- #include <gtest/gtest.h> Correct answer
- #include <test.h>
- #include <iostream>
- #include <cpp/test>
Explanation: The <gtest/gtest.h> header enables GoogleTest.
2 Complete the gtest header
#include <____/gtest.h>
#include <gtest/gtest.h>
Explanation: The <gtest/gtest.h> header provides GoogleTest macros.
3 Match each piece to its role
| Term | Meaning |
|---|---|
#include <gtest/gtest.h> |
GoogleTest header |
TEST(Suite, Name) |
Defines a test |
EXPECT_EQ(a, b) |
Checks equality |
RUN_ALL_TESTS() |
Runs all tests |