Unit Testing in C
Unit testing in C means compiling small programs that call your functions and check return values, outputs, and memory behavior. There is no built-in test runner. You add assert, a framework, or a pile of mains.
Detailed Explanation
A C translation unit is a .c file. A test is another .c file that includes your headers, links your objects, and exits 0 on success. make test or ctest runs the binaries. That is the whole toolchain story.
What to test: return codes, output buffers, and the error paths. malloc failure is hard to hit; you inject it with a wrapper or you test the NULL branch by calling the helper that handles it. Undefined behavior is not something you assert away; you run ASan and UBSan on the test binary so a bad index fails the test.
What not to put in a unit test: a full network stack, a sleep that hopes a thread finished, a test that only passes on one endianness without saying so. Those are integration tests. You still want them; you name them differently.
Linking is the C-specific pain. static functions are invisible. You test them through the public API, or you #include the .c in the test (a trick with hygiene costs), or you drop static in a test build. Globals and singletons make tests order-dependent; reset them or pass context pointers.
A test without a framework is:
int fails = 0;
#define EXPECT(c) do { if (!(c)) { fprintf(stderr, "%s:%d %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)
That is enough for a small library. When you want fixtures, cases, and XML output, pick Check or cmocka.
Run tests under sanitizers in CI. A green assert on a use-after-free is a test that got lucky.
Code Examples
#include <stdio.h>
#include <string.h>
static int add(int a, int b) { return a + b; }
int main(void)
{
int fails = 0;
if (add(2, 2) != 4) {
fprintf(stderr, "add(2,2)\n");
fails++;
}
if (strlen("c") != 1) {
fprintf(stderr, "strlen\n");
fails++;
}
return fails == 0 ? 0 : 1;
}#include <stdlib.h>
#include <string.h>
/* The function under test. Tests live in another file that links this. */
char *dup_str(const char *s)
{
size_t n = strlen(s) + 1;
char *p = malloc(n);
if (p == NULL) {
return NULL;
}
memcpy(p, s, n);
return p;
}Common Gotchas
`static` functions cannot be called from another test file
test through the API or build a test-only object.
Exit status is the protocol
`0` is pass. Printing "OK" and returning `1` fails CI.
A test that ignores `malloc` failure in the code under test does not cover the c
A test that ignores `malloc` failure in the code under test does not cover the cleanup path
Compiling tests without `-fsanitize=address` in CI lets UB pass
Compiling tests without `-fsanitize=address` in CI lets UB pass