Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 171 ยท Errors and Debugging

Unit Testing with GoogleTest and Catch2

Learn C++ unit testing - test cases, assertions, fixtures, parameterized tests and matchers in GoogleTest and Catch2, plus CMake setup and a tiny runnable test harness of your own.

A test is a small program that checks that another piece of code does what you expect, and tells you clearly when it does not. Without tests, every change is a gamble: you fix one function and silently break two others. With a fast suite of unit tests, you can refactor, upgrade the compiler or switch an algorithm and know within seconds whether behavior changed. Tests are also the best way to make sanitizers useful, because they supply the code paths those tools check.

C++ has no testing framework in the standard library. The two most widely used third-party choices are GoogleTest (often called gtest, with its mocking library gmock) and Catch2. Both give you test registration, assertion macros with readable failure messages, fixtures, and a command-line runner. They are not available in this site's in-browser runner, so the framework code below is read-only. To still give you something to run, the lesson builds a miniature test harness from scratch, which shows what the frameworks do for you.

What a unit test looks like

Every test follows the same three steps, usually called arrange, act, assert: set up the inputs, call the code under test, and compare the result with the expectation. Here is the function we will test throughout this lesson:

C++
// stats.h
#pragma once
#include <span>
#include <stdexcept>

inline double average(std::span<const double> values) {
    if (values.empty()) {
        throw std::invalid_argument("average of an empty list");
    }
    double sum = 0;
    for (double v : values) {
        sum += v;
    }
    return sum / static_cast<double>(values.size());
}

Good unit tests are small, fast and independent: each one checks one behavior, needs no network or files, and passes or fails no matter which tests ran before it.

GoogleTest

GoogleTest tests are declared with the TEST macro, which takes a suite name and a test name. Assertions come in two flavors: EXPECT_* records a failure and keeps running the test, while ASSERT_* aborts the current test on failure. Use ASSERT_ when later lines would be meaningless or crash (for example, after checking that a pointer is not null).

C++
// stats_test.cpp (GoogleTest) -- read-only; needs the GoogleTest library
#include <gtest/gtest.h>
#include <vector>
#include "stats.h"

TEST(AverageTest, ComputesMeanOfSeveralValues) {
    std::vector<double> data{2.0, 4.0, 9.0};
    EXPECT_DOUBLE_EQ(average(data), 5.0);
}

TEST(AverageTest, SingleValueIsItself) {
    std::vector<double> data{7.5};
    EXPECT_DOUBLE_EQ(average(data), 7.5);
}

TEST(AverageTest, EmptyInputThrows) {
    std::vector<double> data;
    EXPECT_THROW(average(data), std::invalid_argument);
}

The assertion macros you will use most:

Macro Checks
EXPECT_EQ(a, b), EXPECT_NE(a, b) equality and inequality
EXPECT_LT, EXPECT_LE, EXPECT_GT, EXPECT_GE ordering
EXPECT_TRUE(c), EXPECT_FALSE(c) a condition
EXPECT_DOUBLE_EQ(a, b), EXPECT_NEAR(a, b, tol) floating-point values (never compare with ==)
EXPECT_THROW(stmt, ExceptionType) stmt throws that type
EXPECT_NO_THROW(stmt) stmt throws nothing
EXPECT_STREQ(a, b) C strings

Floating-point comparisons deserve the special macros: 0.1 + 0.2 == 0.3 is false, as you learned in Floating-Point Numbers. Each macro also accepts extra output with <<, for example EXPECT_EQ(x, 3) << "for input " << input;.

Fixtures: shared setup

When several tests need the same objects, a fixture is a class derived from ::testing::Test. The framework creates a fresh instance for every TEST_F, runs SetUp, the test body and TearDown, so tests cannot affect each other:

C++
class AccountTest : public ::testing::Test {
protected:
    void SetUp() override { account = Account("alice", 100); }
    Account account{"", 0};
};

TEST_F(AccountTest, DepositIncreasesBalance) {
    account.deposit(50);
    EXPECT_EQ(account.balance(), 150);
}

TEST_F(AccountTest, OverdraftIsRejected) {
    EXPECT_THROW(account.withdraw(500), InsufficientFunds);
    EXPECT_EQ(account.balance(), 100);     // unchanged after the failure
}

Parameterized tests

If you have one check and many inputs, write the test once and feed it a list. Each input becomes its own test case in the report:

C++
struct Case { std::vector<double> data; double expected; };

class AverageParam : public ::testing::TestWithParam<Case> {};

TEST_P(AverageParam, MatchesExpected) {
    EXPECT_DOUBLE_EQ(average(GetParam().data), GetParam().expected);
}

INSTANTIATE_TEST_SUITE_P(Samples, AverageParam, ::testing::Values(
    Case{{1, 2, 3}, 2.0},
    Case{{10}, 10.0},
    Case{{-4, 4}, 0.0}));

GoogleTest's companion library gmock lets you replace collaborators, such as a database or a clock, with mock objects that record calls and return scripted values. That is how you test a class in isolation from the parts that are slow or unavailable.

Catch2

Catch2 (version 3 is current) takes a lighter approach. A test is a TEST_CASE with a free-form string name, and you check things with REQUIRE (stop on failure) or CHECK (continue). SECTION blocks inside a test case give you fixture behavior without a class: Catch2 runs the test case once per section, re-executing the setup code above it each time.

C++
// stats_test.cpp (Catch2 v3) -- read-only; needs the Catch2 library
#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_approx.hpp>
#include <catch2/matchers/catch_matchers_string.hpp>
#include <vector>
#include "stats.h"

using Catch::Approx;

TEST_CASE("average of a list", "[stats]") {
    std::vector<double> data{2.0, 4.0, 9.0};

    SECTION("mean of several values") {
        REQUIRE(average(data) == Approx(5.0));
    }
    SECTION("adding a value changes the mean") {
        data.push_back(5.0);                       // data is fresh in every section
        REQUIRE(average(data) == Approx(5.0));
    }
    SECTION("empty input throws with a clear message") {
        data.clear();
        REQUIRE_THROWS_WITH(average(data), "average of an empty list");
    }
}

When an assertion fails, Catch2 prints the expression and the values involved, for example REQUIRE( average(data) == Approx(5.0) ) with 4.5 == Approx( 5.0 ), because its macros decompose the expression. Tags such as [stats] let you run a subset: ./tests "[stats]".

Matchers

Both libraries have matchers: composable predicates that describe what a value should look like and explain mismatches in words. Catch2 ships matchers for strings and containers, and gmock provides EXPECT_THAT(value, matcher):

C++
// Catch2
using namespace Catch::Matchers;
REQUIRE_THAT(message, StartsWith("Error") && ContainsSubstring("disk"));
REQUIRE_THAT(result, UnorderedEquals(std::vector<int>{3, 1, 2}));

// GoogleTest + gmock
using ::testing::ElementsAre;
using ::testing::HasSubstr;
EXPECT_THAT(names, ElementsAre("Ada", "Grace", "Alan"));
EXPECT_THAT(message, HasSubstr("disk"));

Matchers shine for containers, where a failure shows which element differed instead of just "false".

A tiny test harness you can run

To see what the frameworks automate, here is a minimal version written with the tools you already know: a registry of named test functions, a macro that records failures, and a runner. It is deliberately small. Real frameworks add fixtures, filtering, XML output, parallel runs and much better messages:

C++ A small test framework

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last test is wrong on purpose, so you can see a failure report (the real mean of 1 and 2 is 1.5), and the program exits with code 1. Notice what the real frameworks do on top of this: they print the values in a failure, run tests in isolation, let you filter by name, and handle crashes. The principle is the same, and the exit code is the contract with your build system: zero means all tests passed. The test names also show a good habit: describe the behavior (empty_input_throws), not the function (test1).

Wiring tests into CMake

Both frameworks integrate with CMake. A typical setup downloads GoogleTest with FetchContent, builds a test executable and registers it so ctest can run it:

CMAKE
include(FetchContent)
FetchContent_Declare(googletest
  URL https://github.com/google/googletest/archive/refs/tags/v1.17.0.tar.gz)
FetchContent_MakeAvailable(googletest)

enable_testing()
add_executable(stats_tests stats_test.cpp)
target_link_libraries(stats_tests PRIVATE GTest::gtest_main)

include(GoogleTest)
gtest_discover_tests(stats_tests)

Catch2 works the same way with Catch2::Catch2WithMain. Then cmake --build build && ctest --test-dir build --output-on-failure runs everything. Add a second build configuration with -fsanitize=address,undefined and run the same tests there too.

Writing tests that stay useful

  • Test behavior, not implementation. A test that breaks whenever you rename a private function is a burden. Check results visible to callers.
  • One reason to fail. Several EXPECT_* lines about the same behavior are fine; unrelated checks belong in separate tests.
  • Cover the edges: empty input, one element, the largest and smallest values, invalid arguments, and the error path (exceptions, as in exceptions).
  • No hidden dependencies: no real clock, random seeds that change, network or shared files. Inject them, as in error-handling strategies.
  • Keep them fast. A suite that runs in seconds gets run on every change; one that takes minutes gets skipped.
  • Write the failing test first when fixing a bug, so the bug cannot come back unnoticed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In GoogleTest, what is the difference between EXPECT_EQ and ASSERT_EQ?

    EXPECT macros are non-fatal, so you see several failures at once. ASSERT macros are fatal for the current test, which is what you want when later lines depend on the check.
  2. 2. How should you compare two double values in a test?

    Rounding errors make exact equality unreliable. Use a macro or helper that allows a small difference.
  3. 3. How does a Catch2 SECTION behave?

    Catch2 enters one section per run of the test case, which gives fixture-like isolation without defining a class.
  4. 4. Why does a test runner return a non-zero exit code when a test fails?

    Tools like ctest and CI pipelines look only at the process exit code. Zero means success, anything else marks the run as failed.
  5. 5. Which is a sign of a well-written unit test?

    Independent, fast, deterministic tests are the ones that get run constantly and trusted when they fail.

Summary

  • Unit tests check small pieces of code in isolation, following arrange, act, assert.
  • GoogleTest uses TEST, TEST_F (fixtures) and TEST_P (parameterized); EXPECT_* continues after a failure, ASSERT_* stops.
  • Catch2 uses TEST_CASE and SECTION, with CHECK and REQUIRE, and prints the values of failed expressions.
  • Use floating-point aware comparisons and matchers for containers and strings.
  • A runner reports through its exit code, which is what CMake's ctest and CI systems rely on.
  • Run your tests under sanitizers, keep them fast and independent, and test edge cases and error paths.

Next: iostream Basics, the standard streams behind input and output in the next chapter.