Test Fixtures
A fixture is the setup and teardown around a test: create the object, run the case, destroy the object even if the case failed. In C you write those two functions yourself or you register them with a framework.
Detailed Explanation
A unit test that mallocs in the case and returns on the first failed assert leaks and leaves files behind. A fixture moves malloc to setup and free to teardown. The runner is supposed to call teardown after a failure. assert from <assert.h> aborts and skips teardown; framework expects that record a failure and return are easier to pair with teardown.
Check calls tcase_add_checked_fixture(tc, setup, teardown). cmocka takes setup / teardown on the group or the test; they receive a void **state you hang the object on. A handwritten runner uses goto out; and a single cleanup label — the same pattern as a careful init.
What belongs in a fixture: a fresh struct Table *, a temporary file path, a directory created with mkdtemp. What does not: process-wide singletons you forgot to reset, a thread you started and did not join, a changed cwd that the next test inherits. If you chdir in setup, chdir back in teardown, or do not chdir.
Isolation is the point. Two tests that share a writable global are one test in disguise. If setup is slow (opening a real database), you have an integration fixture; still tear it down, still do not share writable state.
Failed setup should skip the test and skip teardown or run a partial teardown that only frees what setup finished. Document which. A teardown that frees a pointer setup never set is a crash that hides the setup failure.
Code Examples
#include <stdlib.h>
#include <stdio.h>
struct Bag { int *data; int n; };
static int setup(struct Bag *b)
{
b->n = 2;
b->data = malloc((size_t)b->n * sizeof *b->data);
if (b->data == NULL) {
return -1;
}
b->data[0] = 1;
b->data[1] = 2;
return 0;
}
static void teardown(struct Bag *b)
{
free(b->data);
b->data = NULL;
}
static int test_sum(void)
{
struct Bag b = { 0 };
int rc = 1;
if (setup(&b) != 0) {
return 1;
}
if (b.data[0] + b.data[1] != 3) {
goto out;
}
rc = 0;
out:
teardown(&b);
return rc;
}
int main(void)
{
return test_sum();
}Common Gotchas
`assert` in the test body aborts and skips teardown
use a framework expect, or clean up before you assert.
Teardown must tolerate a half-built object if setup can fail mid-way
`free(NULL)` is your friend.
A fixture that `chdir`s or umasks and does not restore pollutes the next case
A fixture that `chdir`s or umasks and does not restore pollutes the next case
Sharing one heap object across tests without resetting it makes order matter
Sharing one heap object across tests without resetting it makes order matter