Programming Search⌘K

Conceptcore

Test double

Also called test doubles, imposter.

A test double is an object that takes the place of a real component in a test. It has the same interface, so the code under test uses it as if it were real.

Applies to
core-languages

Idea

A unit often depends on other components: a database, a mail server, a clock, a payment service. In a test, these components are a problem. They can be slow, they can be absent, they can give answers that the test cannot control, or they can have effects that the test must not cause, such as a real email. Meszaros calls such a component a depended-on component (DOC). A test double is an object that replaces a DOC during a test. It does not have to behave like the real component. It only has to provide the same interface, so that the system under test (SUT) uses it as if it were real.2 The name comes from the stunt double of the film industry.2

A double gives the test two things that the real component does not. It is a control point: the test decides what the DOC returns to the SUT, which Meszaros calls the indirect inputs. It is also an observation point: the test can see what the SUT sends to the DOC, which he calls the indirect outputs.2 This page uses the five names that Meszaros defined in xUnit Test Patterns.1 Unit testing covers the test itself: its phases, its framework, and when a test with real collaborators is the better choice.

How it works

The five kinds differ in what the test does with them.2

Kind What it does What the test checks
Dummy fills a parameter that the SUT must receive but does not use nothing; a call to it is a bug
Stub returns canned answers, the indirect inputs the result or state of the SUT
Spy a stub that also records the calls it gets the recorded calls, after the SUT has run
Mock holds the expected calls before the SUT runs, and fails at the first unexpected call the calls, during and at the end of the run
Fake a working but lighter version of the real component, such as a store in memory the result or state of the SUT

The function register below needs a user store, a mailer, a clock and a log. The test gives it one double of each kind except the mock. The dummy log raises an error if the SUT uses it. On this path the SUT must not write to the log, so the dummy also checks that.

def register(email, users, mailer, clock, log):
    if users.exists(email):
        log.write(f"duplicate: {email}")
        return "taken"
    users.add(email, clock.now())
    mailer.send(email, "Welcome!")
    return "created"


class DummyLog:  # dummy: fills a parameter and must never be used
    def write(self, line):
        raise AssertionError("the dummy log was used")


class StubClock:  # stub: gives a canned answer
    def now(self):
        return "2000-01-01T00:00:00Z"


class SpyMailer:  # spy: records the calls for later checks
    def __init__(self):
        self.sent = []

    def send(self, to, body):
        self.sent.append((to, body))


class FakeUsers:  # fake: a working store that keeps the rows in a dict
    def __init__(self):
        self.rows = {}

    def exists(self, email):
        return email in self.rows

    def add(self, email, created):
        self.rows[email] = created


users, mailer = FakeUsers(), SpyMailer()
print(register("ada@example.com", users, mailer, StubClock(), DummyLog()))
print("state:", users.rows)
print("calls:", mailer.sent)
Output
created
state: {'ada@example.com': '2000-01-01T00:00:00Z'}
calls: [('ada@example.com', 'Welcome!')]

A mock differs from a spy in when it checks. The test gives the mock its expectations before the SUT runs. The mock compares each call with them as it arrives, and a final verify reports the calls that did not come. Meszaros says that a mock is more than a stub with assertions, because the test uses it in a different way.2 Here the mock expects no mail for an email that is taken. The second version of register sends the mail before it checks the store, and the mock stops it at once.

def register(email, users, mailer):
    if users.exists(email):
        return "taken"
    users.add(email)
    mailer.send(email, "Welcome!")
    return "created"


def register_buggy(email, users, mailer):
    mailer.send(email, "Welcome!")  # sends before the check
    if users.exists(email):
        return "taken"
    users.add(email)
    return "created"


class MockMailer:  # mock: knows the expected calls before the SUT runs
    def __init__(self, expected):
        self.expected = list(expected)

    def send(self, to, body):
        if not self.expected:
            raise AssertionError(f"unexpected call send({to!r}, {body!r})")
        want = self.expected.pop(0)
        if (to, body) != want:
            raise AssertionError(f"send({to!r}, {body!r}), expected send{want!r}")

    def verify(self):
        if self.expected:
            raise AssertionError(f"calls not made: {self.expected}")


class TakenUsers:  # stub: every email is taken
    def exists(self, email):
        return True


for unit in (register, register_buggy):
    mailer = MockMailer(expected=[])  # a taken email must send no mail
    try:
        unit("ada@example.com", TakenUsers(), mailer)
        mailer.verify()
        print(f"{unit.__name__}: pass")
    except AssertionError as error:
        print(f"{unit.__name__}: fail: {error}")
Output
register: pass
register_buggy: fail: unexpected call send('ada@example.com', 'Welcome!')

Fowler names the two styles of check. State verification looks at the result and the state of the SUT and its fakes after the run. Behaviour verification looks at the calls that the SUT made. A mock always uses behaviour verification. A stub can serve either style.3

Most doubles are not written by hand. A mock library builds a configurable double at run time. Python's unittest.mock.Mock creates an attribute the first time the test reads it, returns another Mock from every call by default, and records each call in mock_calls.4 The function create_autospec copies the attributes and the call signatures of a real class. A call with the wrong arguments then raises TypeError, and the assertion methods match a call whether its arguments were passed by position or by name.5

from unittest import mock


class Mailer:
    def send(self, to, body):
        raise NotImplementedError("talks to an SMTP server")


def welcome(email, mailer):
    mailer.send(email, "Welcome!")


mailer = mock.create_autospec(Mailer, instance=True)
welcome("ada@example.com", mailer)
mailer.send.assert_called_once_with("ada@example.com", "Welcome!")
mailer.send.assert_called_once_with(to="ada@example.com", body="Welcome!")
print(mailer.mock_calls)

try:
    mailer.send("ada@example.com")  # one argument missing
except TypeError as error:
    print("TypeError:", error)
Output
[call.send('ada@example.com', 'Welcome!')]
TypeError: missing a required argument: 'body'

The test can put a double in place only through a seam: a point where the code accepts a component from outside. A parameter is the plainest seam, as above. Other seams are an interface with a constructor parameter (Dependency injection), a function value (Higher-order function), a template parameter in C++, and a struct of function pointers in C. Meszaros lists the ways to install a double as the substitutable dependency patterns.2 Python and JavaScript can also replace an attribute of a module or an object while a test runs, which unittest.mock.patch and mock.method of node:test do.48 Languages differ most in this part, as the examples show.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptStandard library
TypeScriptStandard library
GoIdiom
RustIdiom
KotlinIdiomThe Kotlin standard library has no mock facility; a test passes a class or an object expression that implements an interface. Alternative: MockK or Mockito, which are libraries.
SQLDoes not applyA query has no components to replace.
BashIdiomBash has no mock facility, but the shell finds a function before a builtin or a program with the same name. Alternative: Define a shell function with the name of the command, then source the script under test.
PowerShellLibraryPowerShell has no test doubles in the language or its core modules. Alternative: The Mock command of the Pester module, which replaces a command for the scope of a test.
HTMLDoes not applyMarkup has no components to replace.
CSSDoes not applyStyle rules have no components to replace.
Regular expressionsDoes not applyA pattern has no components to replace.

The example files show the same register function with a fake store and a spy mailer in each language. The table gives the verdict for each tier 1 language.

Language Verdict Form
Python stdlib hand-written classes, or unittest.mock with Mock, create_autospec and patch
JavaScript stdlib object literals, or mock.fn and mock.method of node:test
TypeScript stdlib as JavaScript; an object literal that has the shape of an interface is a double
Java idiom a class that implements an interface, or a java.lang.reflect.Proxy
C idiom a struct of function pointers and a void * context
C++ idiom a subclass that overrides virtual functions, or a type given to a template parameter
C# idiom a class that implements an interface
Go idiom any type with the right methods; testing/fstest and net/http/httptest give fakes
Rust idiom a type that implements a trait; RefCell for a spy behind &self
Kotlin idiom a class or an object expression that implements an interface
PowerShell library the Mock command of the Pester module
Bash idiom a shell function with the name of a command
SQL n/a a query has no components to replace
Regex n/a a pattern has no components to replace
HTML/CSS n/a markup and style rules have no components to replace

The verdict says what the language and its standard library give. Mock libraries exist for the languages marked idiom, but they are outside the standard library. Rust's book says that the standard library has no mock functionality, and it builds a recording double with RefCell.9 Go has no mock package, but its standard library has fakes for tests: fstest.MapFS is a file system in memory, and httptest gives a recorder for HTTP responses and a test server.1011

In Bash, the shell looks for a function with the name of a command before it looks for a builtin or a program on PATH.14 A test script can define a function called curl and then source the script under test, so the script calls the function instead of the program. PowerShell has no doubles in the language, and the Pester module's Mock command replaces a command with another implementation for the scope of a test.13

PythonGitHub
import unittest
from unittest import mock


class Mailer:
    def send(self, to, body):
        raise NotImplementedError("talks to an SMTP server")


def register(email, users, mailer):
    if users.exists(email):
        return "taken"
    users.add(email)
    mailer.send(email, "Welcome!")
    return "created"


class FakeUsers:
    def __init__(self):
        self.emails = set()

    def exists(self, email):
        return email in self.emails

    def add(self, email):
        self.emails.add(email)


class RegisterTest(unittest.TestCase):
    def setUp(self):
        self.users = FakeUsers()
        self.mailer = mock.create_autospec(Mailer, instance=True)

    def test_unused_email_is_stored_and_welcomed(self):
        self.assertEqual(register("ada@example.com", self.users, self.mailer), "created")
        self.assertTrue(self.users.exists("ada@example.com"))
        self.mailer.send.assert_called_once_with("ada@example.com", "Welcome!")

    def test_taken_email_gets_no_mail(self):
        self.users.add("ada@example.com")
        self.assertEqual(register("ada@example.com", self.users, self.mailer), "taken")
        self.mailer.send.assert_not_called()


if __name__ == "__main__":
    unittest.main(verbosity=2)
Error output
test_taken_email_gets_no_mail (test_main.RegisterTest.test_taken_email_gets_no_mail) ... ok
test_unused_email_is_stored_and_welcomed (test_main.RegisterTest.test_unused_email_is_stored_and_welcomed) ... ok

----------------------------------------------------------------------
Ran 2 tests in $TIME

OK
  • Verdict: stdlib. unittest.mock is part of the standard library. It gives Mock, MagicMock, create_autospec and patch.
  • The store is a fake written by hand, because a set states its behaviour in a few lines. The mailer is a mock with a spec, because the test cares only about the call.
  • The assertion methods such as assert_called_once_with and assert_not_called belong to the mock, not to TestCase. A misspelt name such as assret_called_with would be a fresh attribute of the mock, so Mock raises AttributeError for names that start with assert, assret and a few other misspellings, unless the mock is made with unsafe=True.
  • patch replaces a name in a module for the length of a test or a with block. It suits code that does not take its dependencies as parameters, but it ties the test to the name that the code looks up.
#include <print>
#include <set>
#include <string>
#include <utility>
#include <vector>

// A seam at run time: an abstract class with virtual functions.
struct Users {
    virtual ~Users() = default;
    virtual bool exists(const std::string& email) const = 0;
    virtual void add(const std::string& email) = 0;
};

struct FakeUsers : Users {
    std::set<std::string> emails;
    bool exists(const std::string& email) const override { return emails.contains(email); }
    void add(const std::string& email) override { emails.insert(email); }
};

// A seam at compile time: any type with send(to, body) can be the mailer.
template <typename Mailer>
std::string register_user(const std::string& email, Users& users, Mailer& mailer) {
    if (users.exists(email)) {
        return "taken";
    }
    users.add(email);
    mailer.send(email, "Welcome!");
    return "created";
}

struct SpyMailer {
    std::vector<std::pair<std::string, std::string>> sent;
    void send(const std::string& to, const std::string& body) { sent.emplace_back(to, body); }
};

int main() {
    FakeUsers users;
    SpyMailer mailer;
    std::println("{}", register_user("ada@example.com", users, mailer));
    std::println("{}", register_user("ada@example.com", users, mailer));
    for (const auto& [to, body] : mailer.sent) {
        std::println("sent {} to {}", body, to);
    }
}
Output
created
taken
sent Welcome! to ada@example.com
  • Verdict: idiom. The C++ standard library has no mock facility. The language gives two seams.
  • The store is a seam at run time. Users is an abstract class with virtual functions, and FakeUsers overrides them. Each call goes through the vtable.
  • The mailer is a seam at compile time. register_user is a template, so any type with a member send(to, body) works, and the call needs no vtable. The cost is that the template must be visible in a header.
  • A function that is not virtual and not a template cannot be replaced by a double without a change to the code or to the link step.
JavaGitHub
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    interface Users {
        boolean exists(String email);
        void add(String email);
    }

    interface Mailer {
        void send(String to, String body);
    }

    static String register(String email, Users users, Mailer mailer) {
        if (users.exists(email)) {
            return "taken";
        }
        users.add(email);
        mailer.send(email, "Welcome!");
        return "created";
    }

    // A fake: a working store in memory.
    static final class FakeUsers implements Users {
        private final Set<String> emails = new HashSet<>();
        public boolean exists(String email) { return emails.contains(email); }
        public void add(String email) { emails.add(email); }
    }

    // A spy made at run time: a Proxy that records each call to any interface.
    @SuppressWarnings("unchecked")
    static <T> T spy(Class<T> type, List<String> calls) {
        return (T) Proxy.newProxyInstance(
            type.getClassLoader(),
            new Class<?>[] {type},
            (proxy, method, args) -> {
                calls.add(method.getName() + List.of(args));
                return null;
            });
    }

    public static void main(String[] args) {
        Users users = new FakeUsers();
        List<String> calls = new ArrayList<>();
        Mailer mailer = spy(Mailer.class, calls);
        System.out.println(register("ada@example.com", users, mailer));
        System.out.println(register("ada@example.com", users, mailer));
        System.out.println(calls);
    }
}
Output
created
taken
[send[ada@example.com, Welcome!]]
  • Verdict: idiom. The standard library has no mock framework. The usual seam is an interface, and a test class implements it.
  • java.lang.reflect.Proxy.newProxyInstance makes an object at run time that implements the given interfaces. Each call goes to one InvocationHandler, which here records the method name and the arguments.
  • A proxy works only for interfaces, not for classes. A double for a class needs a subclass, so a final class or a final method cannot be replaced this way.
  • List.of(args) copies the arguments of each call into the record. A handler for a method with no parameters gets null for args, so a general spy must check for it.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

/* A seam in C: a struct of function pointers and a context pointer. */
typedef struct {
    bool (*exists)(void *ctx, const char *email);
    void (*add)(void *ctx, const char *email);
    void *ctx;
} Users;

typedef struct {
    void (*send)(void *ctx, const char *to, const char *body);
    void *ctx;
} Mailer;

static const char *register_user(const char *email, Users users, Mailer mailer) {
    if (users.exists(users.ctx, email)) {
        return "taken";
    }
    users.add(users.ctx, email);
    mailer.send(mailer.ctx, email, "Welcome!");
    return "created";
}

/* A fake store: a fixed array in memory. */
typedef struct {
    char emails[8][64];
    int count;
} FakeStore;

static bool fake_exists(void *ctx, const char *email) {
    FakeStore *store = ctx;
    for (int i = 0; i < store->count; i++) {
        if (strcmp(store->emails[i], email) == 0) {
            return true;
        }
    }
    return false;
}

static void fake_add(void *ctx, const char *email) {
    FakeStore *store = ctx;
    if (store->count == 8) {
        return; /* full: a fake must not write past its array */
    }
    snprintf(store->emails[store->count++], sizeof store->emails[0], "%s", email);
}

/* A spy: counts the calls and keeps the last recipient. */
typedef struct {
    int calls;
    char last_to[64];
} SpyLog;

static void spy_send(void *ctx, const char *to, const char *body) {
    SpyLog *log = ctx;
    log->calls++;
    snprintf(log->last_to, sizeof log->last_to, "%s", to);
    (void)body;
}

int main(void) {
    FakeStore store = {0};
    SpyLog log = {0};
    Users users = {fake_exists, fake_add, &store};
    Mailer mailer = {spy_send, &log};
    printf("%s\n", register_user("ada@example.com", users, mailer));
    printf("%s\n", register_user("ada@example.com", users, mailer));
    printf("send called %d time(s), last to %s\n", log.calls, log.last_to);
    return 0;
}
Output
created
taken
send called 1 time(s), last to ada@example.com
  • Verdict: idiom. C has no interfaces. The seam is a struct of function pointers with a void * context, which is a vtable written by hand.
  • Each double casts the context back to its own type. The compiler cannot check that the context and the functions match, so a mistake there is undefined behaviour.
  • The fake store has a fixed size, and fake_add checks the bound before it writes. A fake in C has the same memory bugs as other C code, and an unchecked fake turns a test into an out-of-bounds write.
  • The spy keeps only a count and the last recipient. A spy that records every call needs a buffer that grows, which C does not give.
using System;
using System.Collections.Generic;

interface IUsers
{
    bool Exists(string email);
    void Add(string email);
}

interface IMailer
{
    void Send(string to, string body);
}

// A fake: a working store in memory.
sealed class FakeUsers : IUsers
{
    private readonly HashSet<string> emails = new();
    public bool Exists(string email) => emails.Contains(email);
    public void Add(string email) => emails.Add(email);
}

// A spy: records each call for the test to read.
sealed class SpyMailer : IMailer
{
    public List<(string To, string Body)> Sent { get; } = new();
    public void Send(string to, string body) => Sent.Add((to, body));
}

static class Program
{
    static string Register(string email, IUsers users, IMailer mailer)
    {
        if (users.Exists(email))
        {
            return "taken";
        }
        users.Add(email);
        mailer.Send(email, "Welcome!");
        return "created";
    }

    static void Main()
    {
        var users = new FakeUsers();
        var mailer = new SpyMailer();
        Console.WriteLine(Register("ada@example.com", users, mailer));
        Console.WriteLine(Register("ada@example.com", users, mailer));
        Console.WriteLine(string.Join(", ", mailer.Sent));
    }
}
Output
created
taken
(ada@example.com, Welcome!)
  • Verdict: idiom. .NET has no mock framework in its base class library. The seam is an interface, and the test passes a class that implements it.
  • The spy keeps its calls in a list of named tuples. A tuple prints its fields in parentheses, as the last line shows.
  • A double must implement every member of the interface. A large interface makes every double large, which is one reason to keep interfaces small.
  • Methods that are not virtual cannot be replaced by a subclass, so code that a test must replace works through an interface or a delegate.
JavaScriptGitHub
import { test, mock } from "node:test";
import assert from "node:assert/strict";

function register(email, users, mailer) {
  if (users.exists(email)) {
    return "taken";
  }
  users.add(email);
  mailer.send(email, "Welcome!");
  return "created";
}

class FakeUsers {
  #emails = new Set();
  exists(email) {
    return this.#emails.has(email);
  }
  add(email) {
    this.#emails.add(email);
  }
}

test("an unused email is stored and welcomed", () => {
  const users = new FakeUsers();
  const mailer = { send: mock.fn() };
  assert.equal(register("ada@example.com", users, mailer), "created");
  assert.ok(users.exists("ada@example.com"));
  assert.equal(mailer.send.mock.callCount(), 1);
  assert.deepEqual(mailer.send.mock.calls[0].arguments, ["ada@example.com", "Welcome!"]);
});

test("a taken email gets no mail", () => {
  const users = new FakeUsers();
  users.add("ada@example.com");
  const mailer = { send: mock.fn() };
  assert.equal(register("ada@example.com", users, mailer), "taken");
  assert.equal(mailer.send.mock.callCount(), 0);
});
Output
✔ an unused email is stored and welcomed ($TIME)
✔ a taken email gets no mail ($TIME)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms $TIME
  • Verdict: stdlib. node:test has a mock object. mock.fn() makes a spy function, and mock.method() replaces a method of an object for the length of a test.
  • The spy records each call in mock.calls, with its arguments, its result and its this value. mock.callCount() gives the number of calls.
  • Any object with the right methods works as a double, because JavaScript checks no types. The fake store keeps its data in a private field #emails.
  • node:test also has mock.timers, a fake for setTimeout, setInterval and Date, so a test can move the clock without waiting.
TypeScriptGitHub
interface Users {
  exists(email: string): boolean;
  add(email: string): void;
}

interface Mailer {
  send(to: string, body: string): void;
}

function register(email: string, users: Users, mailer: Mailer): string {
  if (users.exists(email)) {
    return "taken";
  }
  users.add(email);
  mailer.send(email, "Welcome!");
  return "created";
}

// A fake: a class that implements Users with a Set.
class FakeUsers implements Users {
  private emails = new Set<string>();
  exists(email: string): boolean {
    return this.emails.has(email);
  }
  add(email: string): void {
    this.emails.add(email);
  }
}

// A spy: an object literal with the shape of Mailer, and no class at all.
const sent: Array<[string, string]> = [];
const spyMailer: Mailer = {
  send(to, body) {
    sent.push([to, body]);
  },
};

const users = new FakeUsers();
console.log(register("ada@example.com", users, spyMailer));
console.log(register("ada@example.com", users, spyMailer));
console.log(sent);
Output
created
taken
[ [ 'ada@example.com', 'Welcome!' ] ]
  • Verdict: stdlib. TypeScript runs on Node.js, so it has the same node:test mocks as JavaScript. This example writes its doubles by hand.
  • TypeScript checks types by structure. The object literal spyMailer has no class, but it has the shape of Mailer, so the compiler accepts it. The parameters to and body get their types from the interface.
  • class FakeUsers implements Users asks the compiler to check that the fake has every method of the interface. When the interface gains a method, the fake fails to compile until it has the method too.
  • The types are erased before the program runs. A double built at run time, such as a Proxy, is checked only by the type that the test gives it.
package main

import (
	"fmt"
	"io/fs"
	"strings"
	"testing/fstest"
)

type Users interface {
	Exists(email string) bool
	Add(email string)
}

type Mailer interface {
	Send(to, body string)
}

func Register(email string, users Users, mailer Mailer) string {
	if users.Exists(email) {
		return "taken"
	}
	users.Add(email)
	mailer.Send(email, "Welcome!")
	return "created"
}

// fakeUsers satisfies Users without naming it: Go interfaces are implicit.
type fakeUsers map[string]bool

func (f fakeUsers) Exists(email string) bool { return f[email] }
func (f fakeUsers) Add(email string)          { f[email] = true }

// spyMailer records each call.
type spyMailer struct{ sent []string }

func (s *spyMailer) Send(to, body string) { s.sent = append(s.sent, to+": "+body) }

// CountLines reads a file through fs.FS, so a test can pass a fake file system.
func CountLines(fsys fs.FS, name string) (int, error) {
	data, err := fs.ReadFile(fsys, name)
	if err != nil {
		return 0, err
	}
	return strings.Count(string(data), "\n"), nil
}

func main() {
	users := fakeUsers{}
	mailer := &spyMailer{}
	fmt.Println(Register("ada@example.com", users, mailer))
	fmt.Println(Register("ada@example.com", users, mailer))
	fmt.Println(mailer.sent)

	fsys := fstest.MapFS{"notes.txt": {Data: []byte("one\ntwo\n")}}
	fmt.Println(CountLines(fsys, "notes.txt"))
	fmt.Println(CountLines(fsys, "missing.txt"))
}
Output
created
taken
[ada@example.com: Welcome!]
2 <nil>
0 open missing.txt: file does not exist
  • Verdict: idiom. Go has no mock package. A type satisfies an interface when it has the methods, with no implements clause, so a double is any small type with those methods.
  • The fake store is a map type with two methods. The spy needs a pointer receiver, because Send changes the slice.
  • The standard library has fakes for tests. testing/fstest.MapFS is a file system in memory, and CountLines accepts it because it takes an fs.FS. net/http/httptest gives ResponseRecorder and a test server.
  • The second call to CountLines shows that the fake also gives the real error for a missing file.
RustGitHub
use std::cell::RefCell;
use std::collections::HashSet;

pub trait Users {
    fn exists(&self, email: &str) -> bool;
    fn add(&mut self, email: &str);
}

pub trait Mailer {
    fn send(&self, to: &str, body: &str);
}

pub fn register(email: &str, users: &mut impl Users, mailer: &impl Mailer) -> &'static str {
    if users.exists(email) {
        return "taken";
    }
    users.add(email);
    mailer.send(email, "Welcome!");
    "created"
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Default)]
    struct FakeUsers(HashSet<String>);

    impl Users for FakeUsers {
        fn exists(&self, email: &str) -> bool {
            self.0.contains(email)
        }
        fn add(&mut self, email: &str) {
            self.0.insert(email.to_string());
        }
    }

    // send takes &self, so the spy needs RefCell to record calls.
    #[derive(Default)]
    struct SpyMailer {
        sent: RefCell<Vec<(String, String)>>,
    }

    impl Mailer for SpyMailer {
        fn send(&self, to: &str, body: &str) {
            self.sent.borrow_mut().push((to.to_string(), body.to_string()));
        }
    }

    #[test]
    fn unused_email_is_stored_and_welcomed() {
        let mut users = FakeUsers::default();
        let mailer = SpyMailer::default();
        assert_eq!(register("ada@example.com", &mut users, &mailer), "created");
        assert!(users.exists("ada@example.com"));
        assert_eq!(
            *mailer.sent.borrow(),
            vec![("ada@example.com".to_string(), "Welcome!".to_string())]
        );
    }

    #[test]
    fn taken_email_gets_no_mail() {
        let mut users = FakeUsers::default();
        users.add("ada@example.com");
        let mailer = SpyMailer::default();
        assert_eq!(register("ada@example.com", &mut users, &mailer), "taken");
        assert!(mailer.sent.borrow().is_empty());
    }
}
Output

running 2 tests
test tests::taken_email_gets_no_mail ... ok
test tests::unused_email_is_stored_and_welcomed ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME
  • Verdict: idiom. The standard library has no mock functionality. A double is a type that implements the trait that the code takes, here through impl Users and impl Mailer.
  • send takes &self, so a spy cannot change its fields in the normal way. RefCell moves the borrow check to run time, which lets the spy push a record through a shared reference. The Rust book uses the same pattern for its mock object.
  • The doubles live in #[cfg(test)] mod tests, so they are compiled only into the test build.
  • register is generic over the traits, so the compiler makes one copy for the doubles and one for the real types. A &dyn Mailer parameter would give one copy and a call through a vtable.

Without RefCell, the spy tries to change a field through &self, and the compiler rejects it with error E0596.

This code does not compile, on purpose.

trait Mailer {
    fn send(&self, to: &str, body: &str);
}

struct SpyMailer {
    sent: Vec<(String, String)>,
}

impl Mailer for SpyMailer {
    fn send(&self, to: &str, body: &str) {
        self.sent.push((to.to_string(), body.to_string()));
    }
}

fn main() {
    let spy = SpyMailer { sent: Vec::new() };
    spy.send("ada@example.com", "Welcome!");
    println!("{}", spy.sent.len());
}
  • Classical and mockist testing. Fowler describes two schools of test-first work. The classical style uses real objects where possible and a double only where the real object is awkward. The mockist style uses a mock for every object with interesting behaviour.3 The choice decides how much a test knows about the code inside the unit.
  • Hand-written and generated doubles. Meszaros separates hard-coded doubles, written for one test, from configurable doubles, which a test sets up and which tools can generate.2 Java's Proxy makes an object that implements any interface at run time and sends each call to one handler.12 The Java example builds a spy with it.
  • Self Shunt. The test class itself implements the interface and acts as the double.2
  • Doubles at the edge of the process. A test can also replace a component outside the process: a local HTTP server, a database in a container, a fake SMTP server. These tests are slower, but they exercise the real client code. httptest.NewServer in Go is a fake server of this kind.11
  • Contract tests. One set of tests runs against both the real component and its fake. When both pass, the fake is a faithful copy for the behaviour that the tests cover (see the last pitfall).

Pitfalls

The mock accepts a method that does not exist

A plain Mock creates any attribute that the test or the SUT reads. When a method of the real class is renamed, code that still calls the old name keeps passing its tests. The Python documentation describes this flaw and calls it general to mocking.5 Here the real method is deliver, but the code calls send.

This code runs but gives a wrong answer on purpose.

from unittest import mock


class Mailer:
    def deliver(self, to, body):  # was called send() before a rename
        raise NotImplementedError("talks to an SMTP server")


def welcome(email, mailer):
    mailer.send(email, "Welcome!")  # still uses the old name


mailer = mock.Mock()
welcome("ada@example.com", mailer)
mailer.send.assert_called_once_with("ada@example.com", "Welcome!")
print("test passed")
Output
test passed

A mock with a spec only has the attributes of the real class. With create_autospec, the same test stops with AttributeError: Mock object has no attribute 'send'.5

This code raises AttributeError, on purpose.

from unittest import mock


class Mailer:
    def deliver(self, to, body):
        raise NotImplementedError("talks to an SMTP server")


def welcome(email, mailer):
    mailer.send(email, "Welcome!")


mailer = mock.create_autospec(Mailer, instance=True)
welcome("ada@example.com", mailer)

In a statically typed language, the compiler gives the same protection: a double that implements an interface must have its methods, with the right types.

A default answer that is true

A Mock returns another Mock from every call.4 The run shows that this Mock is true in a Boolean context. A test that forgets to set a return value gets an answer that the SUT reads as yes. Here the store says that every email is taken, so register never reaches the code that the test wanted to check.

This code runs but gives a wrong answer on purpose.

from unittest import mock


def register(email, users, mailer):
    if users.exists(email):
        return "taken"
    users.add(email)
    mailer.send(email, "Welcome!")
    return "created"


users = mock.Mock()  # the test forgot users.exists.return_value = False
mailer = mock.Mock()
print(register("ada@example.com", users, mailer))
answer = users.exists("ada@example.com")
print(type(answer).__name__, bool(answer))
Output
taken
Mock True

Set every return value that the path under test reads, or use a hand-written stub or fake whose answers are explicit.

Over-mocking couples the test to the code

A test that checks each call that the SUT makes describes how the code works, not what it achieves. Meszaros calls this Overspecified Software, a cause of Fragile Tests, and links it to the heavy use of mock objects.6 Fowler makes the same point: mockist tests are coupled to the implementation, and a change in the calls to collaborators usually breaks them.3 Here total_v2 is a correct refactoring of total_v1. It looks up each distinct product once. The test that checks the calls fails, and the test that checks the result passes.

This code runs but gives a wrong answer on purpose.

from unittest import mock


def total_v1(skus, prices):
    return sum(prices.lookup(sku) for sku in skus)


def total_v2(skus, prices):  # refactored: one lookup for each distinct SKU
    cache = {}
    for sku in skus:
        if sku not in cache:
            cache[sku] = prices.lookup(sku)
    return sum(cache[sku] for sku in skus)


def test_interactions(total):  # checks how the price is found
    prices = mock.Mock()
    prices.lookup.side_effect = {"A": 250, "B": 100}.get
    assert total(["A", "B", "A"], prices) == 600
    assert prices.lookup.mock_calls == [mock.call("A"), mock.call("B"), mock.call("A")]


def test_result(total):  # checks what the caller gets
    class StubPrices:
        def lookup(self, sku):
            return {"A": 250, "B": 100}[sku]

    assert total(["A", "B", "A"], StubPrices()) == 600


for total in (total_v1, total_v2):
    for test in (test_interactions, test_result):
        try:
            test(total)
            outcome = "pass"
        except AssertionError:
            outcome = "FAIL"
        print(f"{total.__name__} {test.__name__}: {outcome}")
Output
total_v1 test_interactions: pass
total_v1 test_result: pass
total_v2 test_interactions: FAIL
total_v2 test_result: pass

Check calls only when the call is the behaviour that matters, such as an email that is sent or a payment that is charged. Meszaros gives the principle "Use the Front Door First": test through the public interface where possible.6 A test that replaces so much that it tests its own doubles is the extreme case. Meszaros warns that a double must never replace the part of the SUT that the test is meant to check.2

The fake drifts from the real component

A fake is code, and it can be wrong. Mackinnon, Freeman and Craig gave the example of a mock that returns degrees where the real code returns radians. They concluded that functional tests are still needed.7 Here the real store is a SQLite table whose key ignores case, and the fake is a Python set. The fake accepts the same address twice.

This code runs but gives a wrong answer on purpose.

import sqlite3


class SqlUsers:  # the real store: the key ignores case
    def __init__(self):
        self.db = sqlite3.connect(":memory:")
        self.db.execute("CREATE TABLE users (email TEXT PRIMARY KEY COLLATE NOCASE)")

    def exists(self, email):
        row = self.db.execute("SELECT 1 FROM users WHERE email = ?", (email,))
        return row.fetchone() is not None

    def add(self, email):
        self.db.execute("INSERT INTO users VALUES (?)", (email,))


class FakeUsers:  # the fake: a set, which does not ignore case
    def __init__(self):
        self.emails = set()

    def exists(self, email):
        return email in self.emails

    def add(self, email):
        self.emails.add(email)


def register(email, users):
    if users.exists(email):
        return "taken"
    users.add(email)
    return "created"


for store in (FakeUsers(), SqlUsers()):
    first = register("ada@example.com", store)
    second = register("Ada@Example.com", store)
    print(f"{type(store).__name__}: {first}, {second}")
Output
FakeUsers: created, created
SqlUsers: created, taken

The fix is a contract test: one function that states the behaviour and runs against the real store and the fake. It found the drift, and the fake now folds the case of each address.

import sqlite3


class SqlUsers:
    def __init__(self):
        self.db = sqlite3.connect(":memory:")
        self.db.execute("CREATE TABLE users (email TEXT PRIMARY KEY COLLATE NOCASE)")

    def exists(self, email):
        row = self.db.execute("SELECT 1 FROM users WHERE email = ?", (email,))
        return row.fetchone() is not None

    def add(self, email):
        self.db.execute("INSERT INTO users VALUES (?)", (email,))


class FakeUsers:
    def __init__(self):
        self.emails = set()

    def exists(self, email):
        return email.casefold() in self.emails

    def add(self, email):
        self.emails.add(email.casefold())


def users_contract(make_store):
    store = make_store()
    assert not store.exists("ada@example.com")
    store.add("ada@example.com")
    assert store.exists("ada@example.com")
    assert store.exists("Ada@Example.com"), "the key must ignore case"


for make_store in (SqlUsers, FakeUsers):
    users_contract(make_store)
    print(f"{make_store.__name__}: contract holds")
Output
SqlUsers: contract holds
FakeUsers: contract holds

casefold and COLLATE NOCASE agree for these ASCII addresses. SQLite's NOCASE folds only the 26 ASCII letters, so a contract for addresses in other scripts needs more cases.15

Cost

  • Speed. A double in memory does no input or output, so it answers without a wait for a disk or a network. Meszaros names Slow Tests as one reason to use a double, and he reports a suite that ran 50 times faster after the database was replaced with hash tables in memory.2
  • Code to maintain. Each hand-written double is code with its own bugs (see the last pitfall).7 A mock library removes the code but adds setup lines to each test, and the tests then depend on the API of the library.
  • Coupling. Every call that a test checks is a fact about the implementation. Such tests break when the code changes without a change in behaviour, so they make refactoring cost more.36
  • Confidence. A test with doubles shows that the unit works with the doubles, not with the real components. Meszaros advises at least one test that runs without the double.2 The Python documentation gives the same advice: tests in isolation still need tests of how the units are wired together.5
  • Run-time mocks. unittest.mock creates attributes on first access and records every call.4 A java.lang.reflect.Proxy sends every call through one handler method.12 This work is small next to the cost of the real component, but it is more than a direct call to a hand-written class.

History

  • 2000. Tim Mackinnon, Steve Freeman and Philip Craig presented "Endo-Testing: Unit Testing with Mock Objects" at XP2000. Their mock objects replace domain code with implementations that emulate it and that assert how the code under test uses them.73
  • 2004 and 2007. Martin Fowler published "Mocks Aren't Stubs" in July 2004. In the revision of January 2007, he split state verification from behaviour verification and classical from mockist testing, and he took the vocabulary of Meszaros.3
  • 2007. Gerard Meszaros published xUnit Test Patterns. The book gives Test Double as the general name and defines Dummy Object, Test Stub, Test Spy, Mock Object and Fake Object.12

References

  1. Gerard Meszaros, xUnit Test Patterns, Refactoring Test Code, Addison-Wesley, 2007, Test Double (page 522), Test Stub (page 529), Test Spy (page 538), Mock Object (page 544), Fake Object (page 551), Dummy Object (page 728)
  2. Gerard Meszaros, Test Double, xunitpatterns.com, the problem statement; How It Works; the variations Test Stub, Test Spy, Mock Object, Fake Object and Dummy Object; the warning on Fragile Tests
  3. Martin Fowler, Mocks Aren't Stubs, revised 2 January 2007, The Difference Between Mocks and Stubs; Classical and Mockist Testing; Coupling Tests to Implementations; Significant Revisions
  4. The Python Standard Library, unittest.mock, Python 3.14, The Mock Class; return_value; mock_calls; call
  5. The Python Standard Library, unittest.mock, Python 3.14, Autospeccing; create_autospec
  6. Gerard Meszaros, Fragile Test, xunitpatterns.com, Cause: Overspecified Software
  7. Tim Mackinnon, Steve Freeman and Philip Craig, Endo-Testing, Unit Testing with Mock Objects, XP2000, Introduction; Not Just Stubs; Limitations of Mock Objects
  8. Node.js documentation, Test runner (node:test), Mocking; Class MockTracker; Class MockTimers
  9. The Rust Programming Language, 15.5 RefCell and the Interior Mutability Pattern, A Use Case for Interior Mutability, Mock Objects
  10. Go standard library, package testing/fstest, type MapFS
  11. Go standard library, package net/http/httptest, package overview; ResponseRecorder; NewServer
  12. Java SE 25 API, java.lang.reflect.Proxy, class description; newProxyInstance
  13. Pester documentation, Mock, Description
  14. Bash Reference Manual, 3.7.2 Command Search and Execution, step 1
  15. SQLite documentation, Datatypes In SQLite, 7. Collating Sequences (NOCASE)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/BWXSXK/text.yaml