Testing and code coverage
Unit tests on the host, mocks, HIL, coverage and static analysis.
Why embedded code is under-tested, and how to fix it
"It needs the hardware" is the usual reason firmware has few automated tests. Most of the logic does not need hardware at all: parsers, state machines, filters, protocol handling, scheduling decisions. The trick is structuring the code so that logic can be compiled and run on a PC, quickly and thousands of times a day, and keeping the hardware-dependent part thin.
The test pyramid for firmware
| Level | Runs on | Speed | Catches |
|---|---|---|---|
| Unit tests | Host PC | Milliseconds | Logic errors in modules |
| Integration tests | Host, with simulated hardware | Seconds | Modules working together |
| Hardware-in-the-loop (HIL) | Real target with a test rig | Minutes | Drivers, timing, real peripherals |
| System and field tests | Complete products | Hours to weeks | Environment, reliability, user scenarios |
Most tests should be at the bottom: fast, cheap and run on every commit.
Unit testing on the host
Frameworks: Unity (with CMock and Ceedling, popular for C), CppUTest, GoogleTest (C++, also for C code), Catch2, or Zephyr's ztest and native_sim target.
A unit test, here written as a tiny self-checking program so it runs in the browser, showing the shape a Unity test takes:
#include <stdio.h>
#include <stdint.h>
/* Code under test: parse "T=21.5" into tenths of a degree. Returns 0 on success. */
static int parse_temp(const char *s, int16_t *out) {
if (s[0] != 'T' || s[1] != '=') return -1;
int sign = 1, i = 2, whole = 0, tenths = 0, digits = 0;
if (s[i] == '-') { sign = -1; i++; }
while (s[i] >= '0' && s[i] <= '9') { whole = whole * 10 + (s[i++] - '0'); digits++; }
if (!digits) return -1;
if (s[i] == '.') { i++; if (s[i] < '0' || s[i] > '9') return -1; tenths = s[i++] - '0'; }
if (s[i] != '\0') return -1;
*out = (int16_t)(sign * (whole * 10 + tenths));
return 0;
}
/* A minimal test harness in the style of Unity's TEST_ASSERT_EQUAL. */
static int failures, tests;
#define CHECK_EQ(expected, actual) do { tests++; if ((expected) != (actual)) { failures++; \
printf("FAIL line %d: expected %d, got %d\n", __LINE__, (int)(expected), (int)(actual)); } } while (0)
int main(void) {
int16_t t = 0;
CHECK_EQ(0, parse_temp("T=21.5", &t)); CHECK_EQ(215, t);
CHECK_EQ(0, parse_temp("T=-4.2", &t)); CHECK_EQ(-42, t);
CHECK_EQ(0, parse_temp("T=7", &t)); CHECK_EQ(70, t);
CHECK_EQ(-1, parse_temp("T=", &t)); /* no digits */
CHECK_EQ(-1, parse_temp("X=21.5", &t)); /* wrong prefix */
CHECK_EQ(-1, parse_temp("T=21.", &t)); /* dangling point */
CHECK_EQ(-1, parse_temp("T=21.5C", &t)); /* trailing junk */
printf("%d checks, %d failed\n", tests, failures);
return failures != 0;
}
Good tests cover the normal case, boundaries, and every error path. Error paths are where field bugs live.
Breaking the dependency on hardware
To run driver-adjacent code on a PC, replace the hardware with test doubles:
| Double | What it does | Example |
|---|---|---|
| Stub | Returns canned values | adc_read() always returns 2048 |
| Fake | A working simplified implementation | An in-memory flash that tracks erases and writes |
| Mock | Records calls and checks expectations | "expect i2c_write(0x48, {0x01, 0x60}) once" (CMock generates these from headers) |
| Spy | Records calls for later inspection | Captures every GPIO write |
Ways to substitute them, from simplest:
- Link-time substitution: the test build links
fake_i2c.cinstead ofi2c_stm32.c. Requires drivers behind a header-defined interface. - Function pointers / interfaces: the code under test receives its dependencies (see driver design).
- Register-level fakes: point register macros at RAM structs during tests and assert on the written values.
Time is a dependency too: route get_ms() and delays through an interface so tests can advance time instantly.
Hardware-in-the-loop
HIL tests run the real firmware on real hardware, with the test rig controlling inputs and observing outputs: a PC or test controller drives GPIOs, injects CAN or UART messages, simulates sensors with DACs, switches power, and checks responses. Tools range from a second microcontroller board and Python scripts (pytest with pyserial) to commercial systems (NI, dSPACE, Vector for automotive). Run a HIL suite nightly and before release.
Simulators fill the gap between: QEMU and Renode emulate whole boards (Renode can simulate multi-node networks), so firmware binaries can be tested in CI without hardware.
Code coverage
Coverage shows which code the tests executed:
| Metric | Measures |
|---|---|
| Statement / line | Was each line executed? |
| Branch / decision | Was each branch of each if taken both ways? |
| MC/DC | Did each condition independently affect the decision? Required for the highest safety levels (DO-178C level A, ISO 26262 ASIL D recommendations) |
On the host: compile with --coverage (gcov), then report with gcovr or lcov. Coverage on the target is possible with semihosting or trace-based tools.
Coverage tells you what is not tested; high coverage does not mean the tests check the right things. A target such as 80% line coverage for logic modules, with every error path tested, is a reasonable practice.
Static analysis
Tools that find bugs without running the code:
- Compiler warnings:
-Wall -Wextra -Werrorplus-Wconversion,-Wshadow,-Wdouble-promotion,-Wformat=2. - cppcheck, clang-tidy, clang static analyzer (scan-build): free.
- MISRA C checkers and commercial analysers (PC-lint Plus, Polyspace, Coverity, Parasoft, Helix QAC) for safety and security projects.
- Sanitizers in host test builds: AddressSanitizer (buffer overflows, use-after-free), UndefinedBehaviorSanitizer (overflow, bad shifts), which catch problems the target would silently tolerate.
CI/CD for firmware
A practical pipeline on every pull request:
- Build every target configuration (and fail on warnings).
- Run host unit tests with sanitizers and coverage.
- Run static analysis.
- Check binary size against budgets.
- Run emulator tests (QEMU/Renode) where available.
- Nightly or on merge: flash a HIL rig and run hardware tests.
- On release: build reproducibly, sign the image, archive the ELF and map file.
Pitfall: Tests that only run on the developer's machine are not tests. If CI does not run them on every change, they stop being maintained within weeks.
Interview question: How do you unit test firmware that talks to hardware?
Answer: Separate logic from hardware access: put drivers behind narrow interfaces (headers implemented per platform, or structs of function pointers) and make time an injectable dependency. Compile the logic on the host with a framework such as Unity or GoogleTest and link fakes, stubs or generated mocks (CMock) in place of drivers, so tests can script hardware responses including errors and timeouts and check the commands sent. Test the thin driver layer itself with register-level fakes and on hardware-in-the-loop rigs. Run everything in CI with sanitizers and coverage.
Interview question: What would you put in a CI pipeline for a firmware project?
Answer: Builds of every target and configuration with warnings as errors; host unit tests run with AddressSanitizer and UBSan and a coverage report; static analysis (clang-tidy, cppcheck, MISRA checker where required); binary size and RAM budget checks from the map file; emulator-based tests in QEMU or Renode; a nightly or merge-triggered hardware-in-the-loop run on real boards; and for releases, reproducible signed builds with the ELF, map file and version metadata archived for field debugging.
Build it: unit tests that actually catch bugs
This is step 2 of the module project. The heart-rate calculation is the watch's core feature, and every change to it must be checked by unit tests before release. In this lab you write the tests. The checks then run them against the real function and against five broken versions ("mutants"), each with a bug developers really make. Good tests pass the real code and fail every mutant.
Lab: Write unit tests that kill the mutants
The function under test, bpm(rr, n), takes n beat-to-beat intervals in milliseconds (0 to 64 of them) and returns the heart rate in beats per minute:
- Only intervals from 300 to 2000 ms inclusive are valid (200 down to 30 bpm); the others are noise from wrist movement and are skipped.
- With fewer than 2 valid intervals it returns 0 (no reading).
- Otherwise it returns
60000 / (average of the valid intervals), where the average is the sum divided by the count, both in integers (rounded down each time).
Write test_bpm(f). It calls the function f with inputs you choose and reports each result with expect(got, want), which counts a failure when they differ. Think about what could go wrong: the range ends, the count rule, the order of the divisions, and a long list of slow beats whose sum gets big.
Going deeper
Interview question: How would you test a greenhouse controller's firmware automatically?
Answer: Unit-test the logic (pump rules, fault detection, parsers) on a PC with fakes for the hardware, run hardware-in-the-loop tests where a test rig simulates the sensors and checks the outputs, and run both in CI on every commit with coverage reported. Each requirement maps to at least one test, so a regression shows exactly what broke.
Interview question: What is hardware-in-the-loop testing?
Answer: Running the real firmware on the real target hardware while a test system controls its inputs and checks its outputs: driving GPIOs, injecting bus messages, simulating sensors with DACs or emulators, switching power and measuring responses. It tests drivers, timing and integration that host tests cannot. Running a HIL suite automatically, nightly or on merge, catches regressions on real hardware.
Interview question: How would you test code that depends on time, such as timeouts?
Answer: Route all time through an interface, such as a get_ticks function and delay functions, and in tests replace it with a fake clock the test advances explicitly. Tests can then jump forward by an hour instantly, check behaviour exactly at a timeout boundary, and simulate the counter wrapping, without real waiting or flakiness.
Explain it: In your own words, explain how you can unit test firmware logic on a PC without the hardware.
Answer: Structure the code so the logic, such as parsers, state machines, filters and protocol handling, does not touch hardware directly but calls small interfaces for anything hardware-related, including time. For tests, compile that logic for the PC with a test framework and link fake implementations of those interfaces that return scripted values, simulate errors and record what was written. Each test then sets up a scenario, calls the code and checks the results in milliseconds, and the suite runs automatically on every change.