Section 10.35

Mock versus stub versus fake

Definition

A mock, a stub and a fake are three kinds of test double: an object that replaces, during a test, a component that the tested code calls. A stub returns answers prepared in advance. A mock holds a list of expected calls and fails the test when the actual calls differ. A fake is a working but simplified implementation, such as storage kept in memory. The difference that matters: a stub controls what the code receives, a mock checks what the code sends, and a fake actually does the work.

The idea

A unit test §10.1, a test of one small piece of code on its own, should be fast, repeatable and able to reach every path through that code. The real components the code calls often prevent all three. A settings module writes to flash memory §6.6, which is slow, wears out with repeated writes, and keeps data from one test to the next. A network client waits for a server that may be down. Error paths are the hardest: making a real flash chip report “full” at exactly the moment a test needs it is difficult. A test double removes these obstacles. The code under test calls the same interface, a set of functions with fixed names and parameters, and cannot tell from the calls alone that the component behind it is not real.

Gerard Meszaros introduced the umbrella term test double in his 2007 book xUnit Test Patterns, after the stunt double who stands in for an actor [496]; Martin Fowler’s essay “Mocks Aren’t Stubs” spread the distinctions [497]. Like a stunt double, a test double only has to look right from where the camera stands, which here is the interface. The analogy stops there. A test double can differ from the real component in ways the interface does not show: how long a call takes, which errors can occur, whether data survives a restart, and how long the component keeps using memory the caller lent it. Those differences decide what a passing test proves.

How it works

The seam. A test needs a place where the real component can be swapped for a double without editing the code under test. Three common seams are:

The kinds. Meszaros distinguishes five.

Libraries use these names loosely. In Python’s §12.23 unittest.mock, one Mock object can serve as a stub, a spy or a mock. In Google’s C++ library gMock, ON_CALL sets a default answer, which is stub behavior, and EXPECT_CALL sets an expectation, which is mock behavior. What an object does decides its kind.

The contract. Every double implements only part of the real component’s contract, the full set of promises the component makes to its callers. For each double, write down how it behaves in each of these dimensions, because the code under test may depend on any of them.

Worked example

The code under test is a function save_threshold(v). It rejects values above 100 and otherwise writes v, as 1 byte, under the key thr through a key-value store. The real store keeps its data in flash memory. Its write function kv_write(key, buf, len, done) returns at once, does the write in the background, and calls done when the data is safely stored, several milliseconds later. Until done runs, the real store may read the caller’s buffer buf at any moment. Its contract allows values of at most 255 bytes. When the flash is full, it reports the error -ENOSPC, meaning no space left on the device.

Three tests use three doubles. Before each test the stored value is 7, and the new value is 8.

Now a defect. Suppose save_threshold puts the 8 into a 1-byte buffer on its own stack, the memory a function uses for its local variables, calls kv_write, and returns. After a function returns, the next function called reuses its stack memory.

The fake read the buffer at the moment of the call. That is one of the timings the real store allows, and the only one under which a stack buffer is harmless. The test covered the most forgiving case and none of the others.

The fake therefore supports claims about the logic of save_threshold and none about storage. Its timing, its errors (-ENOSPC never occurs), its persistence (the table vanishes when the test ends, and no power loss can cut a write off halfway) and its buffer ownership all differ from the real store’s.

Stated precisely

Let RR be the real component and DD the double. For one run of the code under test, a response history is everything the component does in reply to the code’s calls: return values, error codes, when each callback runs, what is still stored after a restart, and when the component reads or writes the caller’s memory. Let H(R)H(R) be the set of response histories the real component’s contract allows, and H(D)H(D) the set the double produces during the tests. Two conditions decide what a passing test with DD shows about the code running with RR.

  1. Faithfulness: H(D)⊆H(R)H(D) \subseteq H(R), meaning every history the double produces is one the real component could produce. If this fails, the code can pass by relying on behavior the real component never shows. A fake that accepts a value of 300 bytes, when the real store’s limit is 255, passes a caller that fails on the device.

  2. Coverage: the claim extends only to the histories the tests actually produced. Every history in H(R)H(R) that the double never produces, such as a late buffer read, a full store or a power loss in the middle of a write, is untested. The stack-buffer defect above lives in such a history.

A mock adds a third element. Its list of expected calls is part of the test oracle §10.5, the check that decides pass or fail. That list is correct only if the requirement demands exactly those calls, no more and no fewer.

Limits and common mistakes

A double is only as good as its author’s knowledge of the real component. A fake is itself a model of the real component and needs its own tests. Running one shared set of tests against both the fake and the real component, sometimes called a contract test, checks that the two agree on the behavior those tests cover.

A mock that spells out the exact sequence of internal calls makes the test fail after harmless changes, such as merging two writes into one, and still passes code that makes the expected calls with a wrong effect. Expect only the calls the requirement demands, and check effects where they can be observed.

A pass with doubles says nothing about the connection to the real component. Each double needs a matching integration test §10.2 with the real component, at least for the behavior the double omits.

A fake is not a simulation of the hardware. A fake of flash storage kept in memory has no erase blocks, no wear and no torn writes §8.19. Behavior after a power loss needs the real storage and power-loss injection §8.38, which cuts the power at chosen moments during a write.

The labels are not standard across libraries, so a report that says “the store was mocked” does not tell a reader what was checked. State the kind of double and what it omits.

Questions answered

Which timing, error, or persistence semantics does the replacement omit?

The omitted semantics, meaning the behaviors of the real component that the replacement does not reproduce, are specific to each replacement and must be written down for it, by comparing the double with the real component’s contract in each dimension: timing, errors, persistence, ordering and concurrency, ownership of memory, and limits. A replacement, also called a test double, is the stub, mock or fake that stands in for a real component during a test. A typical fake of flash storage kept in memory omits:

A stub omits everything except its prepared answers. A mock omits the effect of the calls it checks.

Base the test’s claim on what the double does implement, for example “the function reports failure when a write returns -ENOSPC”. Then test each omitted behavior that matters to the claim with the real component: an integration test for timing and buffer ownership, and power-loss injection on the real device for persistence.

Related entries: Unit test (§10.1), Integration test (§10.2), Asynchronous completion (§9.28), Hardware abstraction layer (HAL) (§6.42), Power-loss injection (§8.38), Ownership (§4.2). Further reading: [496, 497].