// EXPECT_* — non-fatal: test continues on failure// ASSERT_* — fatal: test stops on failureEXPECT_EQ(a, b); // a == bEXPECT_NE(a, b); // a != bEXPECT_LT(a, b); // a < bEXPECT_LE(a, b); // a <= bEXPECT_GT(a, b); // a > bEXPECT_GE(a, b); // a >= bEXPECT_TRUE(condition);EXPECT_FALSE(condition);EXPECT_STREQ(s1, s2); // C-string equalityEXPECT_STRNE(s1, s2);EXPECT_FLOAT_EQ(f1, f2); // float with toleranceEXPECT_DOUBLE_EQ(d1, d2); // double with toleranceEXPECT_NEAR(a, b, abs_error); // within abs_error// Fatal versionsASSERT_EQ(a, b);ASSERT_TRUE(ptr != nullptr); // stops test if ptr is null
Custom Failure Messages
EXPECT_EQ(result, expected) << "Failed for input: " << input;ASSERT_GT(size, 0) << "Container should not be empty";
Test Fixtures
#include <gtest/gtest.h>#include <vector>// Fixture class — inherits from ::testing::Testclass VectorTest : public ::testing::Test {protected: std::vector<int> v; void SetUp() override { v = {1, 2, 3, 4, 5}; // runs before each test } void TearDown() override { // runs after each test (optional cleanup) }};// Use TEST_F for fixture testsTEST_F(VectorTest, SizeIsCorrect) { EXPECT_EQ(v.size(), 5u);}TEST_F(VectorTest, FirstElement) { EXPECT_EQ(v[0], 1);}TEST_F(VectorTest, PushBack) { v.push_back(6); EXPECT_EQ(v.size(), 6u); EXPECT_EQ(v.back(), 6);}
Parameterized Tests
#include <gtest/gtest.h>// Function to testbool isPrime(int n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;}// Parameterized fixtureclass PrimeTest : public ::testing::TestWithParam<int> {};TEST_P(PrimeTest, IsPrime) { EXPECT_TRUE(isPrime(GetParam()));}INSTANTIATE_TEST_SUITE_P( PrimeValues, PrimeTest, ::testing::Values(2, 3, 5, 7, 11, 13, 17, 19));// Non-prime testclass NonPrimeTest : public ::testing::TestWithParam<int> {};TEST_P(NonPrimeTest, IsNotPrime) { EXPECT_FALSE(isPrime(GetParam()));}INSTANTIATE_TEST_SUITE_P( NonPrimeValues, NonPrimeTest, ::testing::Values(0, 1, 4, 6, 8, 9, 10));
Exception & Death Tests
// Exception testsEXPECT_THROW(throw std::runtime_error("err"), std::runtime_error);EXPECT_NO_THROW(safeFunction());EXPECT_ANY_THROW(riskyFunction());// Death tests — test that code crashes/exits as expectedvoid crashFunc() { int* p = nullptr; *p = 1; }EXPECT_DEATH(crashFunc(), ""); // expects crash (any message)EXPECT_EXIT(exit(1), ::testing::ExitedWithCode(1), "");
# Build and runcmake -B build && cmake --build build./build/my_tests# Run specific test./my_tests --gtest_filter=MathTest.Addition# Run all tests matching pattern./my_tests --gtest_filter=Math*# List all tests./my_tests --gtest_list_tests# Run with CTestcd build && ctest --output-on-failure