C: unit testing with a small macro

A unit test calls a small function with known input and compares the result with the expected value. C has no built-in test framework, but projects use Unity, Check, or CMocka. At heart they all work like the macro here: evaluate a condition, report PASS or FAIL, and count failures.

C
#include <stdio.h>
#include <string.h>

static int failures = 0;

#define CHECK(cond)                      \
  do {                                   \
    if (cond) {                          \
      printf("PASS %s\n", #cond);        \
    } else {                             \
      printf("FAIL %s\n", #cond);        \
      failures++;                        \
    }                                    \
  } while (0)

static int clamp(int value, int low, int high) {
  if (value < low) return low;
  if (value > high) return high;
  return value;
}

static void reverse(char *text) {
  size_t n = strlen(text);
  for (size_t i = 0; i < n / 2; i++) {
    char tmp = text[i];
    text[i] = text[n - 1 - i];
    text[n - 1 - i] = tmp;
  }
}

int main(void) {
  CHECK(clamp(5, 0, 10) == 5);
  CHECK(clamp(-3, 0, 10) == 0);
  CHECK(clamp(99, 0, 10) == 10);

  char word[] = "stressed";
  reverse(word);
  CHECK(strcmp(word, "desserts") == 0);

  printf("failures: %d\n", failures);
  return failures != 0;
}
Read the full lesson