Course contentsShow
← C
Lesson 1174 of 1,21916. Practice and ProjectsFree lesson

Building a minimal custom test harness

Building a minimal custom test harness

What you'll learn: How to create a lightweight, macro-based testing system to verify your code without relying on heavy external libraries.

While professional frameworks like Google Test exist, C programmers often build their own "harness"—a simple structure to run functions and report failures. Think of a test harness like a diagnostic machine in an auto shop. You plug your engine (your code) into the machine, run a series of controlled checks, and look for a green light or a red warning.

The Power of the Macro

To keep testing clean, we use a custom ASSERT macro. Macros are perfect for this because they can capture the exact line number where a failure occurred using the built-in __LINE__ constant. This saves you from hunting through hundreds of lines of code to find which specific check failed.

A Minimal Example

Here is how you can structure a small harness to test a basic add function.

#include <stdio.h>

// A simple counter for our test results
int tests_run = 0;
int tests_failed = 0;

// The macro: checks a condition. If it's false, it prints the error.
#define ASSERT(condition, message) do { \
    tests_run++; \
    if (!(condition)) { \
        printf("[FAIL] Line %d: %s\n", __LINE__, message); \
        tests_failed++; \
    } \
} while (0)

// The function we want to test
int add(int a, int b) {
    return a + b;
}

void run_all_tests() {
    ASSERT(add(2, 2) == 4, "2 + 2 should equal 4");
    ASSERT(add(-1, 1) == 0, "-1 + 1 should equal 0");
    ASSERT(add(0, 0) == 1, "0 + 0 should equal 0"); // This will intentionally fail
}

int main() {
    run_all_tests();
    
    printf("\nTest Summary: %d run, %d failed.\n", tests_run, tests_failed);
    return tests_failed == 0 ? 0 : 1;
}

Why this works

By returning tests_failed == 0 at the end of main, your program communicates with your computer. A return value of 0 means success, while anything else indicates a problem. This allows you to automate your testing; you can write a script that runs this program and only alerts you if the exit code is non-zero.

Building your own harness keeps your project dependencies low and gives you total control over how your results are formatted. It turns "I think this works" into "I know this works."

Key takeaway

A minimal test harness uses macros to verify conditions and provides a clear summary of passes and failures.