GoogleTest
GoogleTest (gtest) is the most common C++ unit-test framework. You write TEST and TEST_F macros, assert with EXPECT_* and ASSERT_*, and run a binary that the library's main drives.
Detailed Explanation
A test is a function the macros register in a global list. TEST(Suite, Name) expands to a class and a method. TEST_F(Fixture, Name) uses a fixture class you wrote, so several tests share SetUp/TearDown and members. The binary links gtest_main (or you write main that calls RUN_ALL_TESTS()).
Assertions come in two strengths. EXPECT_* failures mark the test failed and continue. ASSERT_* failures abort the current function (the test method). Use ASSERT when later lines are meaningless (ASSERT_NE(p, nullptr); EXPECT_EQ(*p, 3);). Use EXPECT when you want every bad field reported.
Names: EXPECT_EQ, NE, LT, LE, GT, GE, TRUE, FALSE, STREQ (C strings), FLOAT_EQ, NEAR, THROW, NO_THROW, DEATH (see death-tests). C++ stream insertion on the assertion appends a message: EXPECT_EQ(a, b) << "id=" << id;.
GoogleTest owns the process. One test that overflows the stack or deadlocks hangs the binary. Death tests spawn a child. Fixtures should not leak across tests: SetUp creates, TearDown (or RAII members) destroys. Prefer RAII members over manual TearDown.
Build: CMake FetchContent or a package manager, GTest::gtest_main, gtest_discover_tests. Compile the tests as C++17 (or whatever your production code needs). Do not #define NDEBUG in test builds if you want assert in the code under test to fire — or do, if you want to test the release path.
gMock lives next door for mocking virtual interfaces. If your types are not virtual, you test with fakes, template parameters, or a small seam. GoogleTest does not require gMock.
TEST names must be valid C++ identifiers. No hyphens. Suites group output; they are not fixtures unless you use TEST_F.
Run a subset: --gtest_filter=Suite.Name, --gtest_filter='*Parse*'. Repeat: --gtest_repeat. Shuffle: --gtest_shuffle to find order dependence.
Code Examples
#include <gtest/gtest.h>
#include <string>
int add(int a, int b) { return a + b; }
TEST(Add, TwoPlusTwo) {
EXPECT_EQ(add(2, 2), 4);
}
TEST(Add, Message) {
std::string who = "ada";
EXPECT_EQ(who.size(), 3u) << who;
}#include <gtest/gtest.h>
#include <vector>
class Vec : public ::testing::Test {
protected:
std::vector<int> v{1, 2};
};
TEST_F(Vec, Size) {
EXPECT_EQ(v.size(), 2u);
}Common Gotchas
`EXPECT_EQ` prints values if they stream
custom types need `operator<<` or `EXPECT_TRUE(a == b)`.
Order-dependent tests
a leaked singleton or a temp file will flake under `--gtest_shuffle`.
Linking two `main`s
use either `gtest_main` or your own `RUN_ALL_TESTS`, not both.