Testing with Catch2#

Catch2 is a C++ testing framework. It lets you write small tests that check whether functions return the expected results.

The current course syllabus, assignment instructions, programming standards, and applicable CSN or college policies take precedence over anything on this website.

Catch2 is pre-installed on Bellagio for course use. For course work, prefer Catch2 version 2 when a single-source or single-header setup is needed.

Do not add a testing framework to an assignment unless the assignment allows it or your instructor tells you to use it.

Basic test file#

A simple Catch2 version 2 test file may look like this:

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

int add(int left, int right)
{
    return left + right;
}

TEST_CASE("add returns the sum of two integers")
{
    REQUIRE(add(2, 3) == 5);
    REQUIRE(add(-1, 1) == 0);
}

This example assumes catch.hpp is in the same directory as the test file, or that your Bellagio environment is already set up to find the Catch2 header.

Students who want to develop and run tests on their own computer may download the standalone Catch2 version 2 header from the official Catch2 release page: Catch2 v2.13.10. Download or copy catch.hpp, then place it in the same directory as test.cpp.

Compile the test:

g++ $CXXFLAGS test.cpp -o test

Run the test:

./test

Testing your own functions#

In a larger program, keep the functions you want to test separate from interactive input and output when possible. A function that calculates a result is easier to test than a function that reads from cin, prints to cout, and changes several variables at once.

Example:

int square(int value)
{
    return value * value;
}

TEST_CASE("square multiplies a value by itself")
{
    REQUIRE(square(4) == 16);
    REQUIRE(square(-3) == 9);
}

Good habits#

  • Start with simple functions.
  • Test normal cases.
  • Test boundary cases.
  • Keep tests readable.
  • Compile and run the actual assignment program too.

Passing tests do not prove that a program is complete. They only show that the checked cases worked.

Note: The page you are viewing
is not sanctioned by CSN.