Mocking HAL Layers in Embedded C: Techniques and Patterns

Mocking HAL Layers in Embedded C: Techniques and Patterns

The biggest obstacle to unit testing embedded firmware is hardware dependency. Your motor controller calls HAL_TIM_PWM_Start. Your sensor driver calls SPI_Transmit. Your bootloader calls FLASH_Erase. None of those exist on your host machine, and even if they did, you would not want them running in a test suite.

The solution is mocking — replacing real hardware calls with test doubles that you control. This post covers three approaches to mocking HAL layers in embedded C: CMock (generated mocks), manual fake implementations, and function pointer injection. You will see real code for each, understand when to use which technique, and learn the design patterns that make your firmware mockable in the first place.

Why HAL Mocking Is Different from Application Mocking

In application software, mocking typically means replacing a class or interface. In embedded C, you are replacing a C function. There are no vtables, no dependency injection containers, no interface keyword. You have function calls, #include directives, and linker symbols.

This changes the approach. You mock in embedded C by one of three mechanisms:

  1. Link substitution — provide a different .c file at link time that defines the same symbols
  2. Preprocessor substitution — #define HAL_GPIO_WritePin mock_GPIO_WritePin in test builds
  3. Function pointer indirection — store a pointer to the implementation and swap it in tests

Each has trade-offs. Link substitution (what CMock uses) is transparent but requires build system support. Preprocessor substitution is simple but clutters headers. Function pointer injection is the most flexible but adds runtime overhead and requires upfront design.

CMock: Generated Mocks from Headers

CMock, part of the Ceedling suite, reads a C header file and generates a complete mock implementation. Given:

/* hal_spi.h */
#ifndef HAL_SPI_H
#define HAL_SPI_H

#include <stdint.h>

typedef enum {
    SPI_OK = 0,
    SPI_ERROR,
    SPI_TIMEOUT
} SPI_Status_t;

SPI_Status_t HAL_SPI_Transmit(uint8_t *data, uint16_t size, uint32_t timeout_ms);
SPI_Status_t HAL_SPI_Receive(uint8_t *data, uint16_t size, uint32_t timeout_ms);
SPI_Status_t HAL_SPI_TransmitReceive(uint8_t *tx, uint8_t *rx,
                                      uint16_t size, uint32_t timeout_ms);

#endif

CMock generates mock_hal_spi.c and mock_hal_spi.h with:

  • HAL_SPI_Transmit_ExpectAndReturn(data, size, timeout_ms, return_value) — set expectation with return value
  • HAL_SPI_Transmit_Expect(data, size, timeout_ms) — expect a call, return default
  • HAL_SPI_Transmit_IgnoreAndReturn(return_value) — ignore all calls, always return this value
  • HAL_SPI_Transmit_StubWithCallback(callback_fn) — call your function instead

Here is a test for a BME280 sensor driver using CMock mocks:

/* test/test_bme280.c */
#include "unity.h"
#include "mock_hal_spi.h"
#include "mock_hal_gpio.h"
#include "bme280.h"

static BME280_Handle_t sensor;

void setUp(void) {
    BME280_Init(&sensor);
}

void tearDown(void) { }

void test_BME280_ReadID_SendsCorrectRegister(void) {
    uint8_t expected_tx[] = {0xD0, 0x00};  /* BME280 chip ID register */
    uint8_t fake_rx[]     = {0x00, 0x60};  /* ID byte is second byte */

    HAL_GPIO_WritePin_Ignore();  /* CS pin toggling, don't care about details */

    /* Expect the transmit+receive with exact byte values */
    HAL_SPI_TransmitReceive_ExpectWithArrayAndReturn(
        expected_tx, 2,
        fake_rx, 2,
        2, 10,
        SPI_OK
    );

    uint8_t chip_id = BME280_ReadChipID(&sensor);
    TEST_ASSERT_EQUAL_HEX8(0x60, chip_id);
}

void test_BME280_ReadID_ReturnsZeroOnTimeout(void) {
    HAL_GPIO_WritePin_Ignore();
    HAL_SPI_TransmitReceive_IgnoreAndReturn(SPI_TIMEOUT);

    uint8_t chip_id = BME280_ReadChipID(&sensor);
    TEST_ASSERT_EQUAL_HEX8(0x00, chip_id);
}

void test_BME280_Init_ConfiguresOversamplingRegisters(void) {
    /* Verify init writes the correct config bytes to the sensor */
    uint8_t osrs_tx[] = {0x74 | 0x80, 0xB7};  /* ctrl_meas register, forced mode */
    HAL_GPIO_WritePin_Ignore();
    HAL_SPI_TransmitReceive_ExpectWithArrayAndReturn(
        osrs_tx, 2, NULL, 2, 2, 10, SPI_OK
    );

    SPI_Status_t result = BME280_Configure(&sensor, BME280_OS_16X, BME280_MODE_FORCED);
    TEST_ASSERT_EQUAL(SPI_OK, result);
}

CMock validates every argument by default. If your production code sends the wrong register address, the test fails immediately with the exact mismatch.

Manual Fakes: When You Need More Control

CMock generated mocks enforce strict call order and argument matching. Sometimes you want looser behavior — a fake UART that buffers data for later inspection, or a fake timer that you advance manually.

A manual fake is a .c file you write by hand that implements the HAL interface with test-friendly behavior:

/* test/fakes/fake_hal_uart.h */
#ifndef FAKE_HAL_UART_H
#define FAKE_HAL_UART_H

#include <stdint.h>
#include <stdbool.h>

#define FAKE_UART_BUF_SIZE 512

/* Call this in setUp() */
void fake_uart_reset(void);

/* Inject bytes as if they arrived from hardware */
void fake_uart_inject_rx(const uint8_t *data, uint16_t len);

/* Read bytes that the firmware "transmitted" */
uint16_t fake_uart_get_tx(uint8_t *out, uint16_t max_len);

/* Was transmit called at all? */
bool fake_uart_tx_was_called(void);

#endif
/* test/fakes/fake_hal_uart.c */
#include "fake_hal_uart.h"
#include "hal_uart.h"
#include <string.h>

static uint8_t rx_buf[FAKE_UART_BUF_SIZE];
static uint16_t rx_len = 0;
static uint16_t rx_pos = 0;

static uint8_t tx_buf[FAKE_UART_BUF_SIZE];
static uint16_t tx_len = 0;

void fake_uart_reset(void) {
    memset(rx_buf, 0, sizeof(rx_buf));
    memset(tx_buf, 0, sizeof(tx_buf));
    rx_len = rx_pos = tx_len = 0;
}

void fake_uart_inject_rx(const uint8_t *data, uint16_t len) {
    uint16_t copy = len < (FAKE_UART_BUF_SIZE - rx_len) ? len : (FAKE_UART_BUF_SIZE - rx_len);
    memcpy(rx_buf + rx_len, data, copy);
    rx_len += copy;
}

uint16_t fake_uart_get_tx(uint8_t *out, uint16_t max_len) {
    uint16_t copy = tx_len < max_len ? tx_len : max_len;
    memcpy(out, tx_buf, copy);
    return copy;
}

bool fake_uart_tx_was_called(void) {
    return tx_len > 0;
}

/* These are the real HAL functions — same signatures, fake bodies */
HAL_Status_t HAL_UART_Transmit(uint8_t *data, uint16_t size, uint32_t timeout) {
    uint16_t copy = size < (FAKE_UART_BUF_SIZE - tx_len) ? size : (FAKE_UART_BUF_SIZE - tx_len);
    memcpy(tx_buf + tx_len, data, copy);
    tx_len += copy;
    return HAL_OK;
}

HAL_Status_t HAL_UART_Receive(uint8_t *data, uint16_t size, uint32_t timeout) {
    if (rx_pos >= rx_len) return HAL_TIMEOUT;
    uint16_t avail = rx_len - rx_pos;
    uint16_t copy = size < avail ? size : avail;
    memcpy(data, rx_buf + rx_pos, copy);
    rx_pos += copy;
    return (copy == size) ? HAL_OK : HAL_TIMEOUT;
}

Now your Modbus driver test becomes readable and specific:

void test_Modbus_ReadCoils_SendsCorrectFrame(void) {
    fake_uart_reset();

    /* Read 8 coils starting at address 0x0010, slave ID 1 */
    Modbus_ReadCoils(&bus, 1, 0x0010, 8);

    uint8_t sent[8];
    uint16_t sent_len = fake_uart_get_tx(sent, sizeof(sent));

    TEST_ASSERT_EQUAL(8, sent_len);
    TEST_ASSERT_EQUAL_HEX8(0x01, sent[0]);  /* Slave ID */
    TEST_ASSERT_EQUAL_HEX8(0x01, sent[1]);  /* Function code: Read Coils */
    TEST_ASSERT_EQUAL_HEX8(0x00, sent[2]);  /* Start address high */
    TEST_ASSERT_EQUAL_HEX8(0x10, sent[3]);  /* Start address low */
    TEST_ASSERT_EQUAL_HEX8(0x00, sent[4]);  /* Quantity high */
    TEST_ASSERT_EQUAL_HEX8(0x08, sent[5]);  /* Quantity low */
}

void test_Modbus_ParseResponse_ExtractsCoilValues(void) {
    fake_uart_reset();

    /* Inject a valid Modbus response */
    uint8_t response[] = {0x01, 0x01, 0x01, 0b00110101, 0x90, 0x98};
    fake_uart_inject_rx(response, sizeof(response));

    uint8_t coils[8];
    Modbus_Status_t status = Modbus_ReadCoilsResponse(&bus, coils, 8);

    TEST_ASSERT_EQUAL(MODBUS_OK, status);
    TEST_ASSERT_EQUAL(1, coils[0]);
    TEST_ASSERT_EQUAL(0, coils[1]);
    TEST_ASSERT_EQUAL(1, coils[2]);
}

Function Pointer Injection

The most flexible approach: store HAL function pointers in a struct and swap them in tests. This requires upfront design but gives you complete control at runtime without touching the build system.

/* src/hal_interface.h */
typedef struct {
    void     (*gpio_write)(uint32_t pin, uint8_t state);
    uint8_t  (*gpio_read)(uint32_t pin);
    uint32_t (*get_tick_ms)(void);
    void     (*delay_ms)(uint32_t ms);
} HAL_Interface_t;

/* src/led_controller.h */
typedef struct {
    const HAL_Interface_t *hal;
    uint32_t blink_pin;
    uint32_t blink_period_ms;
    uint8_t  blink_state;
} LedController_t;

void LedController_Init(LedController_t *ctrl, const HAL_Interface_t *hal,
                         uint32_t pin, uint32_t period_ms);
void LedController_Update(LedController_t *ctrl);
/* src/led_controller.c */
void LedController_Update(LedController_t *ctrl) {
    uint32_t now = ctrl->hal->get_tick_ms();
    static uint32_t last_toggle = 0;

    if (now - last_toggle >= ctrl->blink_period_ms) {
        ctrl->blink_state ^= 1;
        ctrl->hal->gpio_write(ctrl->blink_pin, ctrl->blink_state);
        last_toggle = now;
    }
}

In tests, substitute test implementations:

/* test/test_led_controller.c */
#include "unity.h"
#include "led_controller.h"

static uint32_t fake_tick = 0;
static uint8_t  gpio_last_state = 0xFF;
static uint32_t gpio_last_pin   = 0;
static int      gpio_write_count = 0;

static void fake_gpio_write(uint32_t pin, uint8_t state) {
    gpio_last_pin   = pin;
    gpio_last_state = state;
    gpio_write_count++;
}

static uint8_t fake_gpio_read(uint32_t pin) { return gpio_last_state; }
static uint32_t fake_get_tick(void) { return fake_tick; }
static void fake_delay(uint32_t ms) { fake_tick += ms; }

static const HAL_Interface_t test_hal = {
    .gpio_write  = fake_gpio_write,
    .gpio_read   = fake_gpio_read,
    .get_tick_ms = fake_get_tick,
    .delay_ms    = fake_delay,
};

static LedController_t ctrl;

void setUp(void) {
    fake_tick = 0;
    gpio_last_state = 0xFF;
    gpio_write_count = 0;
    LedController_Init(&ctrl, &test_hal, 13, 500);
}

void tearDown(void) {}

void test_LedDoesNotToggleBefore500ms(void) {
    fake_tick = 499;
    LedController_Update(&ctrl);
    TEST_ASSERT_EQUAL(0, gpio_write_count);
}

void test_LedTogglesAt500ms(void) {
    fake_tick = 500;
    LedController_Update(&ctrl);
    TEST_ASSERT_EQUAL(1, gpio_write_count);
}

void test_LedTogglesAgainAt1000ms(void) {
    fake_tick = 500;
    LedController_Update(&ctrl);
    fake_tick = 1000;
    LedController_Update(&ctrl);
    TEST_ASSERT_EQUAL(2, gpio_write_count);
}

void test_LedPinIsCorrect(void) {
    fake_tick = 500;
    LedController_Update(&ctrl);
    TEST_ASSERT_EQUAL_UINT32(13, gpio_last_pin);
}

By controlling fake_tick, you can test time-based behavior precisely without any actual delays. Testing "does the LED blink at 500 ms?" takes microseconds on the host rather than waiting 500 real milliseconds.

Choosing the Right Approach

Technique Best For Trade-offs
CMock Strict protocol validation, verifying exact byte sequences, argument matching Requires Ceedling; strict mode can be noisy for high-frequency calls
Manual fakes Stateful behavior (buffers, queues), looser interaction testing More code to write and maintain
Function pointers New code you control, time-based behavior, HAL-agnostic modules Requires upfront architectural decision; adds indirection cost

In practice, most codebases use all three: CMock for HAL functions you cannot change (vendor-supplied STM32 HAL), manual fakes for communication protocols, and function pointer injection for new modules you design from scratch.

Design Principles for Mockable Firmware

Firmware that was not designed for testing is hard to mock. These principles make it easier:

Single responsibility per module. A module that initializes hardware, processes data, and controls an LED is impossible to test in isolation. Split it.

No globals hiding dependencies. If your timer module reads htim1 directly, it is tightly coupled to the peripheral. Pass a TIM_Handle_t * parameter instead so tests can supply a fake.

Thin ISR handlers. Interrupt service routines should only update state or post to a queue. The logic that processes that state lives in a normal function you can call directly in tests.

HAL behind a defined interface. Even if you start with #include "stm32f4xx_hal.h" everywhere, refactoring toward a defined HAL interface struct (or at least a dedicated hal_*.h wrapper header) gives you the seam you need for mocking.

Summary

Mocking HAL layers is not optional for serious embedded firmware testing — it is the foundation. CMock gives you generated mocks in minutes. Manual fakes give you buffer-based behavior testing for protocols. Function pointer injection gives you fully controllable, time-independent behavior testing. Start with CMock if you are on Ceedling, add manual fakes where you need stateful behavior, and design new modules with function pointer injection from day one. The payoff is a test suite that runs in seconds on any machine, catches regressions instantly, and lets you validate timing logic without touching a hardware timer.

Read more

Start now free