How do you unit test embedded C code?
Short answer: Separate hardware access from logic behind thin interfaces (HAL functions, function pointers or link-time substitution), then compile and run the logic on the host PC with a test framework (Unity, CppUTest, GoogleTest, CMocka), replacing hardware functions with fakes or mocks (CMock, FFF, hand-written fakes). Run the tests on every commit in CI, measure coverage, and add on-target and hardware-in-the-loop tests for what only real hardware can show.
Example: testing a debounce module with Unity
/* debounce.h */
#include <stdbool.h>
#include <stdint.h>
typedef struct { uint8_t count; bool state; } debounce_t;
bool debounce_update(debounce_t *d, bool raw); /* call every 1 ms; returns stable state */
/* debounce.c */
bool debounce_update(debounce_t *d, bool raw)
{
if (raw == d->state) { d->count = 0; return d->state; }
if (++d->count >= 5) { d->state = raw; d->count = 0; } /* 5 consecutive samples */
return d->state;
}
/* test_debounce.c — runs on the PC */
#include "unity.h"
#include "debounce.h"
void setUp(void) {}
void tearDown(void) {}
void test_glitch_is_ignored(void)
{
debounce_t d = {0};
debounce_update(&d, true); debounce_update(&d, true);
debounce_update(&d, false); /* bounce back */
for (int i = 0; i < 4; i++) TEST_ASSERT_FALSE(debounce_update(&d, true));
TEST_ASSERT_TRUE(debounce_update(&d, true)); /* 5th consecutive sample */
}
int main(void) { UNITY_BEGIN(); RUN_TEST(test_glitch_is_ignored); return UNITY_END(); }
Techniques for replacing hardware
| Technique | How | Pros/cons |
|---|---|---|
| Link-time substitution | link fake_gpio.c instead of gpio.c in the test build |
simple, no production code changes |
| Function pointers / interfaces | driver struct with ops, tests pass fakes | flexible, small run-time cost |
| Generated mocks (CMock, FFF) | mocks record calls and return programmed values | verifies interactions; tests can become brittle |
| Register-level fakes | point the peripheral base pointer at a RAM struct | tests driver register logic on the host |
| Emulation | run the firmware in QEMU or Renode | tests whole images, including startup and RTOS |
Good practices: test-driven development for logic-heavy modules (parsers, state machines, protocol handling, filters), keep hardware-dependent code thin, run tests with sanitizers (-fsanitize=address,undefined) on the host, and track coverage with gcov/lcov. Book: Test-Driven Development for Embedded C (James Grenning).