Shortest C++ test framework

We only need assert:

#include <cassert>

Usage

A minimal example:

#include <cassert>

int main() {
  assert(0 > 1);
}

Would result in:

Assertion failed: (0 > 1), function main, file main.cpp, line 4.

We can even make the test a bit more descriptive:

assert("a silly comparison" && 0 > 1);

For which we get:

Assertion failed: ("a silly comparison" && 0 > 1), function main, file a.cpp, line 4.

Comparing floating-point values

Since floating-point values are inherently imprecise, you probably don’t want to compare them directly. Instead, you can use something like this:

#include <cmath>

bool almost_equal(double a, double b, double factor = 1.0) {
  double epsilon = factor * std::numeric_limits<double>::epsilon();
  return std::abs(a - b) < epsilon;
}

Home