Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 46 of 50 · c

Unit Testing with CMocka

Duration: 12 mins

CMocka is a lightweight unit‑testing framework for C.

  1. Install via package manager (apt-get install libcmocka-dev).
  2. Write test functions returning void.
  3. Use assert_int_equal, assert_string_equal, etc.
  4. 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).
Previous: Debugging with GDBNext: Static Analysis with clang‑tidy