Unit_testing
Unit Testing in C++
Section titled “Unit Testing in C++”Unit testing is essential for maintaining code quality. This chapter covers testing frameworks and practices in C++.
Popular Testing Frameworks
Section titled “Popular Testing Frameworks”- Google Test (gtest): Feature-rich, used by Google
- Catch2: Modern, header-only, easy to use
- Boost.Test: Part of Boost library
Google Test Example
Section titled “Google Test Example”Basic Test
Section titled “Basic Test”#include <gtest/gtest.h>
// Simple testTEST(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();}Test Fixtures
Section titled “Test Fixtures”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);}Catch2 Example (Header-Only)
Section titled “Catch2 Example (Header-Only)”#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);}Assertions
Section titled “Assertions”| Google Test | Catch2 | Description |
|---|---|---|
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 |
Testing Best Practices
Section titled “Testing Best Practices”- One test per behavior
- Use descriptive test names
- Test edge cases
- Keep tests independent
- Use Arrange-Act-Assert pattern
Integration with CMake
Section titled “Integration with CMake”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)Key Takeaways
Section titled “Key Takeaways”- 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
Next Steps
Section titled “Next Steps”Now let’s learn about debugging tools.
Next Chapter: 53_debugging_tools.md - Debugging with GDB and Valgrind