C++: a small unit-test harness

A unit test checks one behavior of a small piece of code. Frameworks such as GoogleTest, Catch2, and doctest provide assertions, test discovery, and reports, but their core idea is small: evaluate a condition and report if it is false.

C++
#include <iostream>
#include <stdexcept>
#include <string>

int failures = 0;

#define CHECK(cond)                                  \
  do {                                               \
    if (cond) {                                      \
      std::cout << "PASS " #cond "\n";               \
    } else {                                         \
      std::cout << "FAIL " #cond "\n";               \
      ++failures;                                    \
    }                                                \
  } while (0)

template <typename E, typename F>
bool throws(F fn) {
  try {
    fn();
  } catch (const E&) {
    return true;
  } catch (...) {
    return false;
  }
  return false;
}

int parse_percent(const std::string& text) {
  int value = std::stoi(text);
  if (value < 0 || value > 100) {
    throw std::out_of_range("percent out of range");
  }
  return value;
}

int main() {
  CHECK(parse_percent("42") == 42);
  CHECK(parse_percent("0") == 0);
  CHECK(throws<std::out_of_range>([] { parse_percent("101"); }));
  CHECK(throws<std::invalid_argument>([] { parse_percent("abc"); }));
  std::cout << "failures: " << failures << "\n";
}
Read the full lesson