C++ · Advanced level

Advanced level · Module 4: Testing and Performance in C++ · Lesson 1 of 4

Unit Testing with a C++ Framework

Write and run unit tests with GoogleTest or Catch2 integrated into a CMake project.

In this lesson you will

  • Add a test framework to a CMake project
  • Write test cases with assertions, fixtures and parameterised inputs

Key concepts

test caseEXPECT/REQUIRE assertionsfixturesctest

The lesson

Frameworks such as GoogleTest and Catch2 provide test cases, assertions and clear failure reports. Add one to CMake (for example with FetchContent or a package manager), create a separate test executable and register it with ctest.

Put the logic in a library target so both the application and the tests link to it. Tests then exercise the real code without going through main or the command line.

Test behaviour, not implementation details: inputs and expected outputs, boundary values and error cases. Fixtures share setup between related tests.

Step by step

  1. Split the sensor code into a library and an executable in CMake.
  2. Add a test framework and a test executable.
  3. Write tests for parsing and statistics.
  4. Run them with ctest.

Practice activity

Write at least twelve tests for the parsing and statistics library, including error cases.

Expected result: All tests pass with ctest and fail when a seeded bug is introduced.

Check your understanding

  1. Why put the logic in a library target?

    Show answer

    So the application and the tests can both use it.

  2. Which command runs tests registered with CMake?

    Show answer

    ctest.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.