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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Unit Testing with CMocka | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 46 of 50

·c

Unit Testing with CMocka

12 mins

Course progress92%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Test functions must be `void` and accept `void **state`.
  • Use the assertion macros (`assert_*`) to verify expectations.
  • Link with `-lcmocka` and compile with `-I/usr/include/cmocka` if needed.
  • Separate test files (`test_*.c`) from production code.

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).
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonDebugging with GDBContinue to lesson 47Static Analysis with clang‑tidyBack to C Programming Fundamentals curriculum