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:
dependency injection: the code receives the component as a parameter or object instead of creating it;
a table of function pointers, as in a hardware abstraction layer §6.42, a set of functions that hides the details of one chip behind a common interface;
in C, link-time substitution: the test program is linked against a different object file that defines functions with the same names.
The kinds. Meszaros distinguishes five.
A dummy is passed only to fill a parameter and is never used.
A stub returns answers the test prepared: a fixed value, a sequence of values, or an error code. A stub that returns an error on demand is the usual way to reach an error path. The test then checks the state of the code under test, for example that it reported failure; this style is called state verification.
A spy is a stub that also records the calls it receives, for the test to inspect afterwards.
A mock is told in advance which calls to expect, with which arguments, how many times and sometimes in which order, and it fails the test if the actual calls differ. This style is called behavior verification: the test checks what the code did to its components, not only the state the code ended in.
A fake contains a real, simplified implementation: storage kept in a table in memory instead of flash, or a network that delivers instantly. A fake keeps state between calls, so a read after a write returns the written value.
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.
Timing: how long a call takes, and whether completion is reported later through a callback §14.22, a function the caller supplies and the component calls when the work is done.
Errors: which error codes can occur, and when.
Persistence: whether data survives a restart or a power loss.
Ordering and concurrency §9.1: the order in which effects happen, and the thread or interrupt §6.11 in which callbacks run.
Ownership: who owns each buffer, and until when the component may still read memory the caller passed to it.
Limits: capacity, maximum sizes and wear.
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.
Stub. The stub’s write reports
-ENOSPCevery time. The test checks thatsave_threshold(8)reports failure and that the value in use stays 7. This exercises an error path that is hard to reach with real flash.Mock. The mock expects exactly one call: a write of 1 byte with value 8 under the key
thr. The test passes if that call, and no other, happens. A second write, or a write under another key, fails the test.Fake. The fake keeps a table in memory that starts with
thrset to 7. Its write copies the byte from the buffer into the table during the call and keepsdone; afterkv_writehas returned, the test tells the fake to rundone. Aftersave_threshold(8), readingthrfrom the fake returns 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.
With the fake, the test passes: the fake copied the byte before
kv_writereturned.With the mock, the test passes: the call happened once, with the right arguments.
On the device, the real store reads the buffer some milliseconds later, after
save_thresholdhas returned and other calls have overwritten that stack memory. The store writes whatever byte is there, for example 0, and reports success.
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 be the real component and 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 be the set of response histories the real component’s contract allows, and the set the double produces during the tests. Two conditions decide what a passing test with shows about the code running with .
Faithfulness: , 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.
Coverage: the claim extends only to the histories the tests actually produced. Every history in 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:
timing: calls complete at once, where the real store takes milliseconds and reports completion later through a callback;
errors: no full store, no failed write, no corrupted record;
persistence: the data vanishes when the test ends, so nothing is tested about surviving a restart, and no power loss can cut a write off halfway;
ownership: the fake reads the caller’s buffer during the call, where the real store may read it until completion.
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].