Section 10.1

Unit test

Definition

A unit test is a small automated test that runs one unit of a program on inputs the tester chooses and checks the outcome against an expected result. A unit is a piece of code with a stated job, such as a function, a module or a class; it need not be exactly one function or one file. The test replaces what the unit depends on, such as hardware, a clock or storage, with simple stand-ins under its control, so that a failure points at the unit itself.

The idea

Consider the routine in a small device’s firmware, the program built into the device, that decides where in flash memory §6.6, the memory that keeps its content without power, the next record goes. Checking that routine on the device means building the whole firmware, loading it onto a board, driving the device into the right state and reading the memory back with a debugger. A failure could then come from the radio, the scheduler (the part of the operating system that decides which thread runs) or the board as easily as from the routine. Some cases, such as a full memory or a failed write, are hard to produce on purpose at all.

A unit test cuts the routine out of that context. It calls the routine directly, on an ordinary computer, in a fraction of a millisecond, with inputs and dependency behavior that the tester picks, including the hard cases. A test bench for one engine part is a fair picture: the bench feeds the part and measures it in place of the rest of the car. The picture also shows the price. The bench is not the car. Every stand-in behaves the way the tester believes the real dependency behaves, and the test checks the unit only under that belief. That is why the useful question about any unit test is which real behavior its stand-ins replaced.

How it works

A unit test has three parts, often called arrange, act and assert.

  1. Arrange. Build the starting state and the input, and install stand-ins for the unit’s dependencies. Gerard Meszaros named such stand-ins test doubles §10.35, after the stunt doubles of film. A stub returns fixed answers. A mock records the calls it receives and checks them against expectations. A fake is a simplified working version, such as a flash memory kept in an array §14.5 in RAM.

  2. Act. Call the unit, usually once.

  3. Assert. Compare what happened with what should have happened: the returned value, the changed state and the calls the unit made to its stand-ins. The rule that decides is the test oracle §10.5, the rule or mechanism that decides whether an observed outcome is correct. The expected result should come from the requirement, not from the code under test.

A test framework runs many such tests and reports each failure with its input and the mismatch. Each test starts from a fresh state, so that its result does not depend on which tests ran before it. Examples of frameworks are GoogleTest for C++, Unity for C, and Ztest for the Zephyr real-time operating system §6.33. Unit tests are cheap enough to run after every change to the code, so a defect is often caught minutes after it is written.

The unit is chosen by its contract, the stated promise about what it does with each input, not by the layout of the source files: a parser and the small private functions it calls can form one unit. Testing each private function on its own ties the tests to the current internal design without checking more of the behavior that matters.

Worked example

A routine counter_save(v) stores a 1-byte counter value vv at a fixed address in flash memory. Its author forgot one rule of flash: a byte that has been written must be erased before it can be written again. The unit test replaces the flash driver, the code that operates the flash hardware, with a fake: an array of 4096 bytes in RAM that starts with every byte at 0xFF, the value that erased flash reads as, and that stores each written byte exactly as given.

  1. Arrange: create a fresh fake, in which every byte is 0xFF.

  2. Act: call counter_save(0xF0), then counter_save(0x0F).

  3. Assert: read the byte back and expect 0x0F, the last value saved.

The fake holds 0x0F, so the test passes.

On typical flash memory, a write can only change bits from 1 to 0. Only an erase, which acts on a whole page, a fixed block of often a few KiB, sets bits back to 1. The first write turns 1111 1111 (0xFF) into 1111 0000 (0xF0). The second write requests 0000 1111 (0x0F), but it can only clear bits, so each bit ends up as the AND of the stored bit and the requested bit: 1111 0000 AND 0000 1111 gives 0000 0000. The device reads back 0x00, not 0x0F. Some flash parts go further and reject a second write to a location that has not been erased.

The test was right about the routine’s logic under the fake’s contract, which is a memory that can be overwritten freely. The fake had replaced exactly the platform behavior that decides the outcome. The repair to the test is to make the fake follow the rule: store the AND of the old and the new byte, or report an error when a write targets a byte that is not 0xFF. The same test then fails on the host computer and exposes the defect. The improved fake still says nothing about what the real chip does when power fails in the middle of an erase. That claim needs the device.

Stated precisely

Let UU be the unit, ss the starting state, xx the input, RR the real dependencies of UU, DD the set of test doubles that replace them, and OO the oracle, which accepts or rejects an outcome. The unit test passes when OO accepts the outcome of running UU from state ss on input xx with DD in place of RR.

A pass establishes exactly one fact: on that starting state and that input, the unit combined with the doubles produced an outcome that the oracle accepts. The fact carries over to the unit combined with its real dependencies only under one assumption, conformance of the doubles: for the calls this run made, each real dependency would have returned what its double returned and had the effects its double had. The pass says nothing about other inputs or other starting states. A set of unit tests covers the cases it lists. A claim about other cases needs a separate argument, such as the argument of boundary-value testing §10.31, which picks inputs at and next to each limit because off-by-one mistakes show up there.

Unit tests of firmware on a host computer

Firmware is usually cross-compiled §12.1: built on one computer, the host, for the different processor of the device, the target. Unit tests of firmware often run on the host instead, because the host is fast and needs no board. There are two common ways. The first compiles the unit with the host’s own compiler, together with test doubles for the layer of code that touches the hardware. The second builds the firmware for a simulated board. In the Zephyr real-time operating system, the board target native_sim compiles the operating system kernel, the application and its tests into one ordinary Linux program. Ztest is Zephyr’s test framework: a test is declared with the macro ZTEST and checks results with assertions such as zassert_equal. Twister is Zephyr’s test runner: it finds the test applications, builds them for the requested boards, simulated or real, runs them and reports the results.

Such a test runs the production code, but on a different platform, and it cannot see a defect that depends on a part of the platform it replaced.

A host unit test of storage code can therefore support claims about logic: bounds checks, the order of steps, the choice of which record to keep, and the handling of every error the fake can be told to return. The claims that still need the real hardware are those about the replaced platform: that data survives a power cut on the real flash part, that operations meet their deadlines, that the stacks are large enough, that the code behaves correctly while real interrupts and the real driver run alongside it, and that the flash lasts as many erases as the design needs.

Limits and common mistakes

A passing unit test checks only the inputs it ran. As Edsger Dijkstra put it, testing can show the presence of bugs, but never their absence.

A test double encodes an assumption. A double that never fails leaves the unit’s error handling untested. A double that allows behavior the real dependency cannot produce, such as a flash memory that can be overwritten freely, lets the test pass on code that cannot work on the device.

Over-mocking, replacing so much that the test mostly checks its own stand-ins, produces tests that assert the exact sequence of internal calls. Such a test breaks on every harmless change to the code and can still miss a missing external effect.

An expected value computed by calling the code under test, or by copying its formula, repeats the code’s mistakes. The test oracle entry explains how to keep expected values independent.

Units that pass alone can still disagree about the interface between them, for example about byte order §4.21 or about which side frees a buffer. Only an integration test §10.2, which runs real components together, checks that agreement.

A unit test that depends on the real clock, on random values, on shared global state or on the order in which tests run can pass or fail without any change to the code. Such a test is a nondeterministic test §10.38, often called a flaky test.

High code coverage §10.18 from unit tests means that the code ran, not that its results were checked.

Questions answered

Which important platform behavior is replaced by the test environment?

The test environment replaces every part of the platform that the unit touches but that the test does not run for real, and each replaced part is an assumption that the test does not check. For firmware, the program built into a device, whose unit tests run on a host computer, the replaced behavior usually includes:

Write this list down for each unit test, and state which stand-in replaced each item and what the stand-in assumes. The unit test supports claims about the unit’s logic under those assumptions. Every claim that depends on a replaced item, such as data surviving a power cut on the real flash or a deadline being met, still has to be checked by an integration test, which runs real components together, by a system test §10.3, which runs the complete device, or by another test on the hardware.

Related entries: Test oracle (§10.5), Integration test (§10.2), Mock versus stub versus fake (§10.35), Overflow-safe range check (§4.17), Hardware-in-the-loop testing (§10.36), Zephyr RTOS (§6.33), Flash memory (§6.6), Power-loss injection (§8.38).