Skip to content

Unit_testing

Unit testing is essential for maintaining code quality. This chapter covers testing frameworks and practices in C++.

  • Google Test (gtest): Feature-rich, used by Google
  • Catch2: Modern, header-only, easy to use
  • Boost.Test: Part of Boost library
#include <gtest/gtest.h>
// Simple test
TEST(MathTest, Addition) {
EXPECT_EQ(2 + 2, 4);
}
TEST(MathTest, Division) {
EXPECT_EQ(10 / 2, 5);
// Division by zero - expect exception
ASSERT_THROW(10 / 0, std::runtime_error);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
class DatabaseTest : public ::testing::Test {
protected:
void SetUp() override {
db = new Database(":memory:");
}
void TearDown() override {
delete db;
}
Database* db;
};
TEST_F(DatabaseTest, InsertAndQuery) {
db->insert("test", 42);
EXPECT_EQ(db->query("test"), 42);
}
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
TEST_CASE("Math operations") {
REQUIRE(2 + 2 == 4);
CHECK(10 / 2 == 5);
// Multiple assertions
int x = 5;
CHECK(x > 0);
CHECK(x < 10);
}
TEST_CASE("Vectors") {
std::vector<int> v{1, 2, 3};
REQUIRE(v.size() == 3);
CHECK(v[0] == 1);
CHECK(v[1] == 2);
CHECK(v[2] == 3);
}
Google TestCatch2Description
EXPECT_EQ(a, b)REQUIRE(a == b)Equality
EXPECT_NE(a, b)REQUIRE(a != b)Inequality
EXPECT_TRUE(a)REQUIRE(a)True
EXPECT_FALSE(a)REQUIRE(!(a))False
EXPECT_THROW(a, e)REQUIRE_THROWS(a)Exception
  1. One test per behavior
  2. Use descriptive test names
  3. Test edge cases
  4. Keep tests independent
  5. Use Arrange-Act-Assert pattern
enable_testing()
find_package(GTest REQUIRED)
add_executable(tests test.cpp)
target_link_libraries(tests
GTest::GTest
GTest::Main
)
add_test(NAME mytest COMMAND tests)
  • Unit testing catches bugs early
  • Use Google Test or Catch2 for C++ testing
  • Use fixtures for shared setup/teardown
  • Write tests for edge cases and error conditions

Now let’s learn about debugging tools.

Next Chapter: 53_debugging_tools.md - Debugging with GDB and Valgrind