C++ - Unit Testing

Overview

Estimated time: 50–70 minutes

Write reliable tests with GoogleTest or Catch2. Learn assertions, fixtures, and how to wire tests in CMake.

Learning Objectives

  • Write basic test cases and assertions.
  • Integrate a test framework with CMake and run tests.

Prerequisites

Catch2 single-header (v2) example

#define CATCH_CONFIG_MAIN
#include "catch.hpp"
int add(int a,int b){ return a+b; }
TEST_CASE("add works"){ REQUIRE(add(2,3)==5); }

GoogleTest example

#include 
int add(int a,int b){ return a+b; }
TEST(Math, Add){ EXPECT_EQ(add(2,3),5); }
int main(int argc,char**argv){ ::testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }

CMake integration (sketch)

# CMakeLists.txt
add_executable(tests tests.cpp)
# find_package(GTest CONFIG REQUIRED)
# target_link_libraries(tests PRIVATE GTest::gtest GTest::gtest_main)
add_test(NAME unit COMMAND tests)

Common Pitfalls

  • Mixing debug/release artifacts when linking tests—use consistent build type.
  • Not adding tests to CTest; then CI won’t run them.

Checks for Understanding

  1. When to choose Catch2 vs GoogleTest?
  2. How do you register a test so ctest runs it?
Show answers
  1. Pick based on ecosystem and features; both are fine for unit tests.
  2. Use add_test(NAME unit COMMAND tests) in CMake.

Exercises

  1. Write parameterized tests for an average function.
  2. Set up a test target in CMake and run ctest.