Chapter 5 Extention: Introducing doctest

doctest is a software framework for unit testing in C++. Since it is light weight, comparatively easy to use, and free software, we will begin using it for exercises for the remainder of the book.

Appendix B: A development environment for unit testing has instructions for configuring your computer for using doctest.

We’ll begin here with an example from the chapter.

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest.h>
using namespace std;

double absolute_value(double x) {
    if (x < 0) {
        return -x;
    }
    return x;
}

TEST_CASE("Test absolute_value") {
    CHECK(absolute_value(4) == 4);
    CHECK(absolute_value(-4) == 4);
    CHECK(absolute_value(0) == 0);
}

Compiling this test_absolute_value.cpp source file with:

$ g++ text_absolute_value.cpp

and then running:

$ ./a.out

yields:

$ ./a.out
[doctest] doctest version is "2.5.0"
[doctest] run with "--help" for options
===============================================================================
[doctest] test cases: 1 | 1 passed | 0 failed | 0 skipped
[doctest] assertions: 3 | 3 passed | 0 failed |
[doctest] Status: SUCCESS!