# Embedded unit testing without the target hardware

> Embedded unit testing on a laptop catches firmware logic bugs in seconds. How to structure code, pick tools and know what still needs the board.

- Author: Milo Perović, Founder & lead engineer
- Published: 2026-11-16
- Topic: Firmware

Most small firmware teams test on the target board or not at all. That works until the codebase reaches a few tens of thousands of lines, a parser bug ships to a fleet, and every fix needs someone at the bench with a debugger. Embedded unit testing on a laptop, without the target hardware, is the cheapest way we know to stop that from happening.

This post is for founders, product managers and engineers who own firmware for a connected device and want faster, safer changes. We cover how to structure code so it can be tested off-target, which tools are worth the setup, what not to bother testing on the host, and how this fits alongside bench and hardware-in-the-loop work.

## Why embedded unit testing belongs on the host

A unit test that runs on a laptop finishes in milliseconds. A test that needs flashing a board, resetting it and reading a serial log takes tens of seconds at best, and it ties up a board and a person. When the feedback loop is that slow, people stop running tests, and the test suite quietly rots.

Host tests also give you tools the microcontroller cannot. You can run the same code under AddressSanitizer and UBSan, measure line and branch coverage with gcov, and feed a protocol parser thousands of malformed packets in a second. On an STM32L4 or nRF52840 with a few hundred kilobytes of RAM, none of that is practical.

The honest limit is that a host build is not the target. The compiler, word size, endianness assumptions, alignment rules and timing all differ. Host tests prove your logic is right; they do not prove the board works. That is why we treat them as the first layer, not the only one.

## Structure the code so it can be tested

The hard part of testing firmware is rarely the framework. It is code that reads registers, calls the RTOS and makes decisions in the same function. You cannot test that without the chip. The fix is a deliberate split between logic and hardware access.

- **Pure logic modules**: state machines, protocol framing, CRCs, unit conversions, filtering, scheduling decisions, configuration validation. These take inputs and return outputs, with no hardware calls. This is where most bugs live and where host tests pay back fastest.

- **Thin hardware abstraction layer**: small interfaces such as `i2c_write()`, `gpio_set()` or `flash_erase_page()`. Real implementations call the vendor HAL; test builds swap in fakes.

- **Drivers on top of the abstraction**: a sensor driver that talks to the I2C interface rather than to registers can be tested against a fake bus that returns recorded datasheet-style responses.

- **Glue and startup**: clock trees, interrupt vectors, linker scripts. Keep this small and leave it to on-target tests.

We do the swap at link time rather than with function pointers everywhere. The production build links `hal_stm32.c`; the test build links `hal_fake.c`. There is no runtime cost on the device, and the production code does not grow indirection just to satisfy tests.

The same idea applies to the RTOS. If application tasks call queue and semaphore functions through a small wrapper, the logic inside each task can be tested as plain functions. We wrote about keeping task responsibilities narrow in [FreeRTOS task design for small connected devices](https://miloperovic.com/journal/freertos-task-design-for-small-connected-devices/), and narrow tasks are also much easier to test.

## Choosing a framework and toolchain

For C firmware, the choice is less important than picking one and wiring it into the build on day one. The common options:

FrameworkLanguageGood forTrade-off

Unity + CMock (often via Ceedling)CPlain C codebases, generated mocks from headersCeedling adds a Ruby dependency and its own conventions

CppUTestC and C++Mixed codebases, built-in memory leak detectionTest files are C++ even when the code is C

GoogleTest + GoogleMockC++C++ firmware, rich matchersHeavier; awkward for pure C without wrappers

Some vendor SDKs help here too. ESP-IDF ships Unity as a component and has preview support for building some components for a Linux host target, which is useful on ESP32-S3 projects. Check what your SDK version supports before building your own scaffolding.

Whatever you pick, build tests with the host GCC or Clang using the same warning flags as production, plus `-fsanitize=address,undefined`. Run them in CI on every push. A suite that only runs on one engineer's laptop is a suite that stops running.

### Fakes, mocks and recorded data

Generated mocks are convenient but brittle: they assert on the exact order of calls, so a harmless refactor breaks dozens of tests. We prefer hand-written fakes for buses and flash (a fake flash that enforces erase-before-write and page boundaries catches real bugs), and reserve mocks for checking that a specific call happened, such as a watchdog kick or a radio sleep command.

For sensor drivers and parsers, recorded data is worth more than invented data. Capture real I2C transactions, UART streams or radio payloads from a prototype with a logic analyser, and replay them in tests. Edge cases from real hardware, such as a sensor returning a stale value after a brown-out, are the ones nobody thinks to invent.

## What to test on the host and what not to

Not everything earns a host test. Our rough split:

- **Always test on the host**: protocol encoders and decoders, packet framing and CRCs, state machines, configuration and settings migration, ring buffers, time and date handling, retry and back-off logic, OTA image header validation.

- **Test on the host with fakes**: sensor drivers, flash storage layers, power state decisions, command handlers.

- **Test on the target**: interrupt latency, DMA behaviour, clock and peripheral configuration, low-power entry and wake-up, radio performance, anything timing-critical at the microsecond level.

Integer-width and endianness bugs deserve a special mention. A host build on a 64-bit machine can hide overflow that appears on a 32-bit Cortex-M. Use fixed-width types (`uint16_t`, `int32_t`) throughout, avoid relying on the size of `int` or `long`, and serialise multi-byte fields explicitly rather than copying structs onto the wire.

## How host tests fit with bench and HIL testing

We think of firmware verification as three layers. Host unit tests run in seconds and catch logic errors. Hardware-in-the-loop tests run real firmware on real boards with scripted stimuli and catch integration and timing problems; we covered setting that up in [hardware-in-the-loop testing for small firmware teams](https://miloperovic.com/journal/hardware-in-the-loop-testing-for-small-firmware-teams/). Bench and environmental testing then catches what only physics can show you.

Each layer is cheaper per test than the one above it, so the goal is to push every bug as low as possible. If a bug is found on the bench and it turns out to be a logic error, the fix should come with a host test that reproduces it. Over a few months that habit turns the suite into a record of every way the product has broken.

## What we would do on a new project

If you are starting firmware now, or inheriting a codebase with no tests, this is the order we would follow:

- Pick one framework and add a host test target to the build before writing feature code.

- Define a thin hardware abstraction for every bus and peripheral the application touches.

- Write host tests first for parsers, state machines and settings migration, where bugs are most expensive in the field.

- Build tests with sanitizers and production warning flags, and run them in CI on every push.

- Write hand-rolled fakes for flash and buses that enforce real constraints.

- Capture real sensor and radio data from the first prototypes and replay it.

- Turn every field or bench bug that is a logic error into a regression test.

- Track coverage for the logic modules, but do not chase a number for glue code.

None of this needs a large team or an expensive platform. It needs a decision early in the project that firmware logic will be written to be testable, and the discipline to keep the test build green.
