Lesson 46 of 50 · c
Unit Testing with CMocka
Duration: 12 mins
CMocka is a lightweight unit‑testing framework for C.
- Install via package manager (
apt-get install libcmocka-dev). - Write test functions returning
void. - Use
assert_int_equal,assert_string_equal, etc. - Build with
-lcmocka.
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
int add(int a, int b) { return a + b; }
static void test_add(void **state) {
(void) state; // unused
assert_int_equal(add(2,3), 5);
assert_int_equal(add(-1,1), 0);
}
int main(void) {
const struct CMUnitTest tests[] = { cmocka_unit_test(test_add) };
return cmocka_run_group_tests(tests, NULL, NULL);
}
Run with ./test_add – a pass yields a green OK line.
📚 Why Unit Test?
- Detect regressions early.
- Document expected behaviour.
- Encourage design with testable functions (small, pure logic).