Skip to content

Test doubles, seams, and designing for testability

Difficulty: Intermediate

Key concepts

  • test double
  • fake
  • stub
  • spy
  • mock
  • dummy
  • seam
  • interface seam
  • template seam
  • link seam
  • over-mocking
  • testability
  • What the common kinds of test double are (dummy, fake, stub, spy, and mock), and how to choose between them for a given test.
  • What a Seam is, and the four seams C++ offers: an interface, a function parameter, a template parameter, and the link step. What each one costs, and when each one fits.
  • How to test code that calls a library you do not own, without calling the library.
  • Why a test that checks every call can break when the code improves, and how to tell a call that is a requirement from one that is a detail.
  • What “designing for testability” asks of a design, and where it stops being useful.

A dental clinic wants to text each patient the day before an appointment, so fewer people forget. A job on the clinic’s server runs every 15 minutes. The requirements:

# Requirement
R1 Each patient whose appointment starts within the next 24 hours gets one reminder, at the first run that sees it
R2 The text greets the patient and gives the day (“today” or “tomorrow”) and the time
R3 If the SMS network is busy, try again after 100 ms and then 200 ms; if it is still busy, try again at the next run
R4 If the number is rejected as invalid, record that and never send to that appointment again; texting a bad number costs money too

The texts go through an SMS provider. Its C++ library is one plain function, not an interface, and the clinic cannot change it. Every call sends a real message to a real phone and costs money.

That last fact is why this page exists. A test that calls the real function sends texts to whoever owns the number, and a test that waits for real time to pass takes minutes. Before any of the requirements can be tested, the design needs places where a test can put something else.

Seams: where a test can change the behaviour

Section titled “Seams: where a test can change the behaviour”

A seam is a place where the behaviour of code can be changed without editing that code. Every test double needs one: the code under test must reach its collaborator through something the test can point somewhere else. C++ has four common kinds:

Seam How the test replaces the collaborator Chosen Cost
Interface The code holds a reference to an abstract class; the test passes another implementation When the object is made A virtual call; an interface to maintain
Function parameter The code takes a std::function (or a function pointer); the test passes a lambda When the object is made A possible allocation and an indirect call; no class needed
Template parameter The code is a template on the collaborator’s type; the test passes its own type When compiling No run-time cost; the code must be in a header, and errors are longer
Link The code calls a plain function; the test executable links a different definition When linking No change to the code at all; one replacement per executable, usually global state

A fifth, the preprocessor seam (#ifdef TESTING around the real call), also works, but it means the code that is tested is not the code that ships. It is best kept for code that cannot be changed any other way.

The reminder service uses all four. The diagram shows where each one is:

The reminder service and its seams. Solid arrows show the seams as the demo uses them; where tests put something else there, the node names it or a dashed arrow shows it. The vendor function is replaced at the link step.
Text description of the diagram

ReminderService::run calls two free functions from the same library: reminder_text, which is pure and needs no seam, and deliver_with_retry, a template on its waiting function. The service reaches the appointment book and the clock through two interfaces, AppointmentBook and Clock. In the demo these are MemoryBook and a fixed DemoClock; in tests they are MemoryBook and a ManualClock, both fakes. deliver_with_retry sends through the Notifier interface: in production that is the SmsNotifier adapter, and in tests it is a StubNotifier, SpyNotifier, or MockNotifier. The service waits through a Sleeper, a std::function: in production it calls std::this_thread::sleep_for; in tests, a lambda that records the wait. SmsNotifier calls the vendor function vendor::sms_send. The demo links a console stand-in that prints each message; the adapter’s test links fake_vendor_sms.cpp instead, a link seam.

Diagram source (Mermaid)
flowchart LR
subgraph Core["the reminder service"]
  RS["ReminderService::run"]
  DR["deliver_with_retry<br/>(a template on Sleep)"]
  RT["reminder_text<br/>(pure: no seam needed)"]
  RS --> DR
  RS --> RT
end
RS -->|"AppointmentBook (interface)"| MB["MemoryBook<br/>fake, also used by the demo"]
RS -->|"Clock (interface)"| C1["DemoClock in the demo<br/>ManualClock fake in tests"]
DR -->|"Notifier (interface)"| SN["SmsNotifier adapter"]
DR -.->|"Notifier in tests"| D["StubNotifier, SpyNotifier,<br/>MockNotifier"]
RS -->|"Sleeper (function)"| SL["std::this_thread::sleep_for<br/>or a recording lambda"]
SN -->|"vendor::sms_send (link)"| V["vendor library<br/>console stand-in in the demo"]
SN -.->|"link seam in tests"| FV["fake_vendor_sms.cpp"]

The service needs three things from outside: the appointments, a way to send a message, and the time. Each is an interface, defined by what the service needs, not by what the vendor offers:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

reminders.hpp
// Port 1: where appointments come from. The service asks only one question: which
// appointments start in a time window? A database, a file, or a test's in-memory list can
// all answer it. Each port here is an interface: a class whose functions, apart from the
// destructor, are all `virtual ... = 0` (pure virtual), so it cannot be created
// directly; a concrete class derives from it and fills the functions in.
class AppointmentBook {
public:
// A virtual destructor, so that deleting a concrete book through an AppointmentBook
// pointer runs the concrete class's destructor too. `= default`: nothing extra to do.
virtual ~AppointmentBook() = default;
// Returns copies of the appointments with from <= start < to (the window includes
// `from` and excludes `to`), in the order they were booked. `const`: asking does not
// change the book.
[[nodiscard]] virtual std::vector<Appointment> between(Minutes from, Minutes to) const = 0;
};
// What happened when one message was sent. This is the service's own vocabulary: it says
// nothing about any SMS vendor's status codes, which an adapter translates into these three.
enum class SendResult {
sent,
rejected, // the number is not valid; trying again will not help
unavailable, // the network is busy; trying again later may
};
// Port 2: how a message is sent. Not `const`, because sending is an action (and a test
// double may record it). The two strings are passed by const reference: read, not copied.
class Notifier {
public:
virtual ~Notifier() = default;
[[nodiscard]] virtual SendResult send(const std::string& phone, const std::string& text) = 0;
};
// Port 3: what time it is, in minutes since the calendar began. Reading the time through an
// interface, instead of asking the system clock directly, is what lets a test fix the time.
class Clock {
public:
virtual ~Clock() = default;
[[nodiscard]] virtual Minutes now() const = 0;
};

SendResult is the service’s own vocabulary. The vendor’s status codes, 0, 1, and 2, appear nowhere in it; one adapter, later on this page, translates them. That is what makes the service testable without the vendor: nothing in it knows the vendor exists.

The service itself holds references to its three ports and a function for waiting. It owns none of the three: whoever builds it, the demo or a test, owns them, and they must outlive it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

reminders.hpp
// What one run did: how many reminders were sent, rejected, or failed. A plain value.
struct RunReport {
int sent = 0;
int rejected = 0;
int failed = 0; // still unavailable after every attempt; tried on the next run
// `= default` asks the compiler to write ==, comparing the members one by one. That
// lets a test write LLD_CHECK_EQ(service.run(), (RunReport{3, 0, 0})).
friend bool operator==(const RunReport&, const RunReport&) = default;
};
// A Sleeper is any function that takes a duration and returns nothing: "wait this long".
// std::function can hold a lambda, a plain function, or any other callable of that shape,
// so the service does not need to be a template to accept different ones.
using Sleeper = std::function<void(std::chrono::milliseconds)>;
// Reminds each patient once, at the first run within 24 hours of the
// appointment. The book, notifier, and clock must outlive the service.
// It stores references to them, not copies: it owns none of them, which is what lets a test
// keep its own double and look at it after the service has used it. The Sleeper is the one
// thing it owns (a copy, taken by value). `attempts` is the most sends each reminder gets
// in one run, 3 unless the caller says otherwise (a default argument).
class ReminderService {
public:
ReminderService(const AppointmentBook& book, Notifier& notifier, const Clock& clock,
Sleeper sleep, int attempts = 3);
// One pass of the reminder job: sends what is due now and reports what happened.
// Not const: it remembers who has been reminded, for the next run.
RunReport run();
private:
const AppointmentBook& book_;
Notifier& notifier_;
const Clock& clock_;
Sleeper sleep_;
int attempts_;
std::set<int> reminded_; // appointment IDs sent to, or rejected
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

reminders.cpp
// One run of the reminder job. Asks the book for every appointment that starts in the next
// 24 hours, skips the ones already dealt with, sends each of the others a reminder (with
// retries), and counts what happened. Returns those counts; throws nothing of its own.
RunReport ReminderService::run() {
using namespace std::chrono_literals; // lets the code write 24h for "24 hours"
const Minutes now = clock_.now(); // read the time once, so the whole run agrees on it
RunReport report; // every count starts at 0
// The window is [now, now + 24h): an appointment exactly 24 hours away is not due yet.
// between() returns a new vector; the loop keeps it alive until the loop ends.
for (const Appointment& a : book_.between(now, now + 24h)) {
if (reminded_.contains(a.id)) continue; // already sent or rejected: skip it
// reminder_text builds the message as a temporary string. It lives until the switch
// condition is finished, after deliver_with_retry returns, so the reference it holds
// stays valid for every attempt. sleep_ is a named object: Sleep&& binds to it, no copy.
switch (deliver_with_retry(notifier_, a.phone, reminder_text(a, now), attempts_, sleep_)) {
case SendResult::sent:
++report.sent;
reminded_.insert(a.id); // done: later runs skip this appointment
break;
case SendResult::rejected: // a bad number stays bad: do not try again
++report.rejected;
reminded_.insert(a.id);
break;
case SendResult::unavailable:
// Not remembered on purpose: the next run, if the appointment is still in
// the window, tries again.
++report.failed;
break;
}
}
return report;
}
How this code works: ReminderService::run
  1. Read the time once. now is fixed for the whole run, so every appointment is judged against the same moment.
  2. Ask the book for the window. between(now, now + 24h) returns the appointments that start at now or later, and before now + 24h.
  3. Skip what is already done. reminded_ is a set of appointment IDs that the service keeps between runs. An ID is in it if a reminder was sent, or if the number was rejected.
  4. Send, with retries. deliver_with_retry sends the text, retrying while the network is busy, and returns one final SendResult.
  5. Count and remember. sent and rejected both add the ID to reminded_, so later runs skip it. unavailable only counts a failure and does not remember the ID, so the next run tries again, as long as the appointment is still inside the window.

Here is the demo, further down this page, run by run. Its appointments are Asha (10:30 today), Ben (07:45 tomorrow), Chidi (11:00 today, with an invalid number), and Dana (09:00 tomorrow).

Run Window Asha Ben Chidi Dana Report
08:00 08:00 today to 08:00 tomorrow sent sent rejected outside the window 2 sent, 1 rejected
08:00 again the same skipped skipped skipped outside the window all zero
10:00 10:00 today to 10:00 tomorrow skipped skipped skipped sent 1 sent

The second run sends nothing because all three IDs are now in reminded_. Chidi is skipped too, even though no message reached them: a rejected number is not tried again.

The text of a reminder is a pure function, reminder_text. It needs no seam and no double: a test calls it with values and checks the string.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_reminders.cpp
// reminder_text is a pure function: no doubles needed.
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if the condition
// is false; LLD_CHECK_EQ(actual, expected) records one if the two are not equal, and prints
// both. They come from the site's small test header, lld_test.hpp. A failed check does not
// stop the test: the remaining checks still run.
// `day` (24h) and `eight_am` (8h) are constants defined near the top of this file; 10h and
// 30min are std::chrono literals, so 10h + 30min is 630 minutes after the calendar began.
LLD_TEST(the_text_says_today_or_tomorrow_and_the_time) {
// The fields, in order: id, patient, phone, start.
const Appointment morning{1, "Asha", "+15550100", 10h + 30min}; // day 0, 10:30
const Appointment next_day{2, "Ben", "+15550101", day + 7h + 5min}; // day 1, 07:05
// "now" is 08:00 on day 0: the same day as Asha's, the day before Ben's.
LLD_CHECK_EQ(reminder_text(morning, eight_am), "Hi Asha, your appointment is today at 10:30.");
LLD_CHECK_EQ(reminder_text(next_day, eight_am),
"Hi Ben, your appointment is tomorrow at 07:05.");
}

That is the first lesson about doubles: the best test needs none. Every rule that can be a pure function should be one, and then only the code that connects the rules to the outside world needs doubles.

The names below are common but not universal; testing libraries and teams use them differently. This page means:

Kind What it does The test checks Here
Dummy Fills a parameter; never actually used Nothing about it no_wait, in tests where the network is never busy, so it is never called (where it is called, it is a stub that does nothing)
Fake A real, working implementation, simplified: memory instead of a disk The result, and the fake’s state MemoryBook, ManualClock
Stub Gives canned answers; remembers nothing What the code did with the answers StubNotifier
Spy Records how it was used, for the test to look at afterwards The recorded calls, as the test chooses SpyNotifier
Mock Is told beforehand which calls to expect; a strict one, like the one here, fails the test on any other That exactly those calls happened MockNotifier

The first four let the test decide, afterwards, what to look at. A mock decides before the code runs. That difference matters more than any other on this page, and the section on over-mocking shows why.

A fake really does the job, just without the expensive part. The appointment book’s fake keeps a vector and answers the same query the real database would:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

memory_book.hpp
// A complete appointment book kept in memory. Tests use it as a fake:
// it really answers queries, just without a database. The demo uses it
// too, which is common for fakes that are this simple.
// `final`: nothing derives from it. `public AppointmentBook`: it is an AppointmentBook, so
// the service can be given one wherever it expects a book.
class MemoryBook final : public AppointmentBook {
public:
// Adds an appointment at the end. The parameter is a copy the function owns, so it is
// moved into the vector rather than copied a second time.
void book(Appointment appointment) { appointments_.push_back(std::move(appointment)); }
// The same promise as the port: copies of the appointments with from <= start < to,
// in booking order. A plain scan of every appointment, fine for a handful in a test.
// `override` asks the compiler to check that this really replaces the port's function.
[[nodiscard]] std::vector<Appointment> between(Minutes from, Minutes to) const override {
std::vector<Appointment> out;
for (const Appointment& a : appointments_) {
if (from <= a.start && a.start < to) out.push_back(a); // in the window: copy it
}
return out;
}
private:
std::vector<Appointment> appointments_; // in the order they were booked
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

doubles.hpp
// A fake clock: it really tells the time, but the time moves only when the test says so,
// with advance(). A test can go from 08:00 to 09:00 in one line, with no real waiting.
class ManualClock final : public Clock {
public:
explicit ManualClock(Minutes start) : now_(start) {} // the time the test begins at
[[nodiscard]] Minutes now() const override { return now_; }
void advance(Minutes by) { now_ += by; } // a test-only control: move time forward
private:
Minutes now_;
};

Fakes are the most useful doubles, because tests that use them read like ordinary use: book some appointments, move the clock, run. They have one risk: a fake that behaves differently from the real thing makes tests pass that should fail. MemoryBook promises from <= start && start < to, in booking order; a database implementation must keep the same promises, and a contract test, run against both, is how to make sure it does.

Most of the service’s tests use a spy for the notifier. It records each call and answers from a short script, so a test can make the network busy for exactly as many calls as it needs:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

doubles.hpp
// A spy: records every call, in the public vector `calls`, for the test to look at
// afterwards. It answers from a script given to its constructor, front first, and says
// "sent" once the script runs out; with no script (the default), every send is "sent".
class SpyNotifier final : public Notifier {
public:
struct Call {
std::string phone;
std::string text;
};
explicit SpyNotifier(std::deque<SendResult> script = {}) : script_(std::move(script)) {}
[[nodiscard]] SendResult send(const std::string& phone, const std::string& text) override {
calls.push_back({phone, text}); // copies both strings: the caller's may not last
if (script_.empty()) return SendResult::sent; // script used up
const SendResult answer = script_.front(); // the next scripted answer...
script_.pop_front(); // ...removed, so the call after gets the one after it
return answer;
}
// The phones sent to, sorted: tests that use this do not depend on
// the order the service sends in.
[[nodiscard]] std::vector<std::string> phones() const {
std::vector<std::string> out;
for (const Call& c : calls) out.push_back(c.phone);
std::sort(out.begin(), out.end()); // alphabetical order
return out;
}
// The text of the first message to `phone`, or "" if there was none.
[[nodiscard]] std::string text_sent_to(const std::string& phone) const {
for (const Call& c : calls) {
if (c.phone == phone) return c.text; // the first match wins
}
return "";
}
std::vector<Call> calls; // public, so a test can read calls.size() or calls[0].text
private:
std::deque<SendResult> script_; // a deque: removing from the front is cheap
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_reminders.cpp
// Sets up five appointments around the edges of the window [08:00 day 0, 08:00 day 1) and
// proves that exactly the three inside it are reminded. It also checks Asha's text.
LLD_TEST(everyone_with_an_appointment_in_the_next_24_hours_is_reminded) {
MemoryBook book; // the fake book
book.book({1, "Asha", "+15550100", eight_am + 2h});
book.book({2, "Ben", "+15550101", eight_am - 1min}); // a minute too early
book.book({3, "Eve", "+15550104", eight_am}); // first minute inside
book.book({4, "Chidi", "+15550102", eight_am + day - 1min}); // last minute inside
book.book({5, "Dana", "+15550103", eight_am + day}); // a minute too late
ManualClock clock(eight_am); // the fake clock says 08:00, day 0
SpyNotifier notifier; // no script: every send is "sent"
// no_wait, defined near the top of this file, is a function that does nothing. Here the
// network is never busy, so it is never called: it only fills the parameter (a dummy).
ReminderService service(book, notifier, clock, no_wait);
// The extra brackets around RunReport{3, 0, 0} are needed because a macro splits its
// arguments at every comma that is not inside round brackets; braces do not protect them.
LLD_CHECK_EQ(service.run(), (RunReport{3, 0, 0})); // 3 sent, 0 rejected, 0 failed
// Asha, Chidi, and Eve, sorted by phone number, as phones() returns them.
const std::vector<std::string> expected{"+15550100", "+15550102", "+15550104"};
LLD_CHECK(notifier.phones() == expected);
LLD_CHECK_EQ(notifier.text_sent_to("+15550100"),
"Hi Asha, your appointment is today at 10:00.");
}
// One appointment, two runs an hour apart: proves the second run sends nothing more.
LLD_TEST(a_patient_is_reminded_only_once) {
MemoryBook book;
book.book({1, "Asha", "+15550100", eight_am + 2h});
ManualClock clock(eight_am);
SpyNotifier notifier;
ReminderService service(book, notifier, clock, no_wait);
// run() is [[nodiscard]]; static_cast<void> says "the report is ignored on purpose".
static_cast<void>(service.run()); // 08:00: Asha is reminded
clock.advance(1h); // now 09:00; Asha's 10:00 is still in the window
LLD_CHECK_EQ(service.run(), (RunReport{0, 0, 0}));
// 1u is an unsigned 1, to match the unsigned type size() returns.
LLD_CHECK_EQ(notifier.calls.size(), 1u);
}
// Dana's appointment is 25 hours away at first: proves it is not reminded then, but is
// once the clock moves forward enough to bring it inside the window.
LLD_TEST(an_appointment_is_reminded_once_it_comes_within_24_hours) {
MemoryBook book;
book.book({1, "Dana", "+15550103", day + 9h}); // 09:00 on day 1
ManualClock clock(eight_am);
SpyNotifier notifier;
ReminderService service(book, notifier, clock, no_wait);
LLD_CHECK_EQ(service.run(), (RunReport{0, 0, 0})); // window ends 08:00 day 1: not due yet
clock.advance(2h); // 10:00: window ends 10:00 day 1
LLD_CHECK_EQ(service.run(), (RunReport{1, 0, 0}));
LLD_CHECK_EQ(notifier.text_sent_to("+15550103"),
"Hi Dana, your appointment is tomorrow at 09:00.");
}
// The network is busy for the first three sends: proves the first run reports a failure,
// does not remember Asha as done, and the next run sends her reminder.
LLD_TEST(a_reminder_that_failed_is_sent_on_the_next_run) {
MemoryBook book;
book.book({1, "Asha", "+15550100", eight_am + 2h});
ManualClock clock(eight_am);
// The script: busy, busy, busy, then (script used up) sent for every later call.
SpyNotifier notifier({SendResult::unavailable, SendResult::unavailable,
SendResult::unavailable});
ReminderService service(book, notifier, clock, no_wait); // 3 attempts per run (default)
LLD_CHECK_EQ(service.run(), (RunReport{0, 0, 1})); // all three attempts were busy
clock.advance(15min);
LLD_CHECK_EQ(service.run(), (RunReport{1, 0, 0})); // the fourth send gets "sent"
LLD_CHECK_EQ(notifier.calls.size(), 4u); // three attempts, then one that worked
}
How this code works: the spy tests

The first test puts one appointment on each side of each edge of the window. The clock says 08:00 on day 0, so the window is from 08:00 on day 0 up to, but not including, 08:00 on day 1:

Patient Starts In the window? Why
Ben 07:59, day 0 no one minute before now
Eve 08:00, day 0 yes from <= start: the edge counts
Asha 10:00, day 0 yes well inside
Chidi 07:59, day 1 yes the last minute inside
Dana 08:00, day 1 no start < to: the edge does not

So three reminders go out, and the report is RunReport{3, 0, 0}.

The last test scripts the spy to answer “busy” three times. In the first run, deliver_with_retry makes its three attempts (the default), gets “busy” each time, and the service counts one failure without remembering Asha. Fifteen minutes later, Asha is still in the window and the script has run out, so the fourth call is answered “sent”. Four calls in all.

  • The boundaries of R1 are tested on both sides. One appointment starts a minute before the run and one exactly 24 hours after; both are left out. One starts at the very minute of the run and one in the last minute inside the window; both are sent.
  • The checks are on outcomes. Which phones received a message (sorted, so the order of sending does not matter), what Asha’s text said, and how many calls there were in all. The test does not care how the service decided, or in which order it sent.
  • “Once” is checked across runs. A reminder sent at 08:00 is not sent again at 09:00, and a reminder that failed at 08:00 is sent at 08:15. The fake clock makes both a single line.

When the test is about what the service does with an answer, not about the calls, a stub is enough. This one says “busy” to every call, and the waits are recorded by a lambda instead of slept:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

doubles.hpp
// A stub: gives the same canned answer, fixed in its constructor, to every call, and
// remembers nothing (send leaves its parameters unnamed: it never looks at them). Use it
// when the test cares about what the service does with the answer, not about the call.
class StubNotifier final : public Notifier {
public:
explicit StubNotifier(SendResult answer) : answer_(answer) {}
[[nodiscard]] SendResult send(const std::string&, const std::string&) override {
return answer_;
}
private:
SendResult answer_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

doubles.hpp
// Records each wait instead of waiting, so a retry test takes no time.
// The function from sleeper() refers to this object, so it must not
// outlive it.
struct RecordedWaits {
std::vector<std::chrono::milliseconds> waits; // every wait asked for, in order
// Returns a Sleeper (a std::function) wrapping a lambda. `[this]` captures a pointer to
// this RecordedWaits, so each call appends to this object's `waits`; it is that pointer
// that would dangle if the Sleeper outlived the object.
[[nodiscard]] Sleeper sleeper() {
return [this](std::chrono::milliseconds wait) { waits.push_back(wait); };
}
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_reminders.cpp
// The network is always busy: proves that one run makes 3 attempts with two waits between
// them, the second twice the first, and no wait after the last, and then reports a failure.
LLD_TEST(a_busy_network_means_two_growing_waits_then_a_failure) {
MemoryBook book;
book.book({1, "Asha", "+15550100", eight_am + 2h});
ManualClock clock(eight_am);
StubNotifier notifier(SendResult::unavailable); // "busy", to every call
// Declared before the service, so it is destroyed after it: the Sleeper the service
// holds points at `waits`, and must never be used once `waits` is gone.
RecordedWaits waits;
ReminderService service(book, notifier, clock, waits.sleeper());
LLD_CHECK_EQ(service.run(), (RunReport{0, 0, 1}));
// 3 attempts: wait 100 ms after the first, 200 ms after the second, none after the third.
const std::vector<std::chrono::milliseconds> expected{100ms, 200ms};
LLD_CHECK(waits.waits == expected);
}

The recorded waits are the evidence for R3: two waits, of 100 ms and 200 ms, and no third wait after the last attempt. The test takes no time at all.

A mock is given a list of expected calls before the code runs. Any call that is not on the list, comes in a different order, or has different arguments, fails the test; verify() fails it if an expected call never came. Mocking libraries generate such classes; this one is written by hand, so its behaviour is all visible:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

doubles.hpp
// A mock: with expect_send, the test lists the calls it expects, in order, before the
// code runs. A call that was not expected, or that comes in a different order or with
// different arguments, fails the test at once (it is reported as it happens, and the
// test carries on); verify() fails it if an expected call never came.
class MockNotifier final : public Notifier {
public:
void expect_send(std::string phone, std::string text, SendResult answer) { // queue one
expected_.push_back({std::move(phone), std::move(text), answer}); // moved in
}
[[nodiscard]] SendResult send(const std::string& phone, const std::string& text) override {
if (next_ == expected_.size()) { // every expected call has already come
::lld::test::report_failure(__FILE__, __LINE__, "unexpected send to " + phone);
return SendResult::sent; // some answer is needed; the test has already failed
}
const Expected& e = expected_[next_++]; // use the next expectation, then step past it
if (phone != e.phone || text != e.text) { // not the call that was expected next
::lld::test::report_failure(__FILE__, __LINE__,
"send to " + phone + ", expected send to " + e.phone);
}
// __FILE__ and __LINE__, used in the reports, are filled in by the compiler with
// this file's name and the line they are written on, so a failure message points
// here. The leading :: in ::lld::test means "look up lld from the top-level namespace".
// Even a wrong call gets its scripted answer, so the code under test can carry on.
return e.answer;
}
// Called by the test at the end: fails if some expected calls never happened. Without
// it, a test whose code never called send at all would still pass. next_ never goes
// past expected_.size(), so the subtraction below cannot wrap around.
void verify() const {
if (next_ != expected_.size()) { // some expected calls are left over
::lld::test::report_failure(
__FILE__, __LINE__,
std::to_string(expected_.size() - next_) + " expected send(s) never came");
}
}
private:
// One expected call: the arguments it must have, and the answer to give back.
struct Expected {
std::string phone;
std::string text;
SendResult answer;
};
std::vector<Expected> expected_; // in the order the calls must come
std::size_t next_ = 0; // index of the next expected call; all before it came
};

A mock is the right tool when the calls themselves are the requirement. R4 is such a requirement: a rejected number must be sent exactly one message, ever, because each message costs money. The mock says that directly:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_reminders.cpp
// The requirement here is about the calls themselves: a rejected number
// gets exactly one message, ever. A mock states that directly.
// Set up: one expected call, answered "rejected". If the service retried within the run,
// or sent again on the second run, the mock would report an unexpected send.
LLD_TEST(a_rejected_number_is_tried_once_and_never_again) {
MemoryBook book;
book.book({1, "Chidi", "555-0102", eight_am + 2h});
ManualClock clock(eight_am);
MockNotifier notifier;
// The expectation is stated before the service runs: exactly this call, once.
notifier.expect_send("555-0102", "Hi Chidi, your appointment is today at 10:00.",
SendResult::rejected);
ReminderService service(book, notifier, clock, no_wait);
LLD_CHECK_EQ(service.run(), (RunReport{0, 1, 0})); // the one expected call: rejected
clock.advance(1h);
LLD_CHECK_EQ(service.run(), (RunReport{0, 0, 0})); // no call at all: the mock stays quiet
notifier.verify(); // and the expected call did come
}
How this code works: MockNotifier, call by call

The mock keeps a list of expected calls, expected_, and an index, next_, of the next one it is waiting for. Each send goes one of three ways:

  1. Nothing more was expected (next_ has reached the end of the list): report “unexpected send” and answer sent, just so the code under test can carry on.
  2. The next expected call matches the phone and text: step next_ forward and give back the answer stored with it.
  3. It does not match: report the difference, step forward anyway, and still give back the stored answer. This is the second report_failure call in send, the one behind the doubles.hpp:124 lines in the over-mocking section below.

A report does not stop the test: report_failure, from the test header, counts the failure and prints it, and the test goes on.

In the test above:

Step What happens next_
expect_send(...) one expectation is stored: Chidi’s number and text, answer rejected 0
first run, 08:00 the service sends to Chidi; it matches, so the mock answers rejected 1
second run, 09:00 Chidi is in reminded_, so the service does not call send 1
verify() next_ equals the list size, 1, so nothing is reported 1

If the service had retried the rejected number, or sent again at 09:00, that call would have taken the first path and failed the test at that moment.

A spy could check the same thing, by counting calls afterwards. The mock is a little more direct, and it fails at the moment of the unexpected call, where a debugger breakpoint in the mock will stop with the service’s code on the call stack. Either is a reasonable choice here. The mock does pin more than R4 asks for, the exact text, because a hand-written mock with no way to say “any text” has to; a mocking library’s wildcards would let the test say only what matters. What is not reasonable is using a mock where the order and number of calls are not a requirement, which is the subject of a later section.

R3 needs the code to wait. A test that really waited would take 300 ms for each busy-network case, and a test with a real network would not be repeatable at all. So waiting is a seam too, and it shows the two seams that need no interface.

The retry loop is a function template. Its waiting function is a template parameter, constrained by a concept to be callable with a duration:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

reminders.hpp
// Sends once, and if the network is busy, waits and tries again, up to
// `attempts` times in all, doubling the wait each time from 100 ms. A
// rejected number is never retried. `sleep` is called with each wait;
// it is a template parameter, so a test can pass a lambda that records
// the waits instead of sleeping, with no virtual call and no allocation.
// Returns the result of the last send: sent or rejected as soon as one comes, or unavailable
// if every attempt was busy. It always sends at least once, even if `attempts` is 0 or less.
//
// `template <class Sleep>`: Sleep stands for whatever type the caller's waiting function has
// (a lambda, a plain function, a std::function); the compiler writes one version of this
// function for each such type. The `requires` line is a constraint (a C++20 concept): this
// function exists only for a Sleep that can be called with a duration in milliseconds,
// so passing something else gives a clear compile error here. `Sleep&& sleep` accepts both
// a named function object and a temporary one without copying it. Inside, `sleep` is used
// as a named object (an lvalue), which is why the constraint checks `Sleep&`.
template <class Sleep>
requires std::invocable<Sleep&, std::chrono::milliseconds>
[[nodiscard]] SendResult deliver_with_retry(Notifier& notifier, const std::string& phone,
const std::string& text, int attempts, Sleep&& sleep) {
std::chrono::milliseconds wait{100}; // the first wait; doubled after each one
// No condition between the two semicolons: the loop runs until a `return` leaves it.
for (int attempt = 1;; ++attempt) {
const SendResult result = notifier.send(phone, text);
// Stop if the answer is final (sent or rejected: retrying cannot change it), or if
// this was the last attempt allowed. Either way, hand back this attempt's result.
if (result != SendResult::unavailable || attempt >= attempts) return result;
sleep(wait); // busy, and attempts remain: wait, then go round again
wait *= 2; // 100 ms, then 200 ms, then 400 ms, ...
}
}
How this code works: deliver_with_retry

The loop has no exit condition of its own; the only way out is the return. Each time round, it sends once, then decides:

  • the answer is sent or rejected: final, so return it;
  • the answer is unavailable and this was the last attempt: return unavailable;
  • otherwise: wait, double the wait, and go round again.

With 3 attempts, as the service uses, and a network that is always busy:

attempt send returns Returns now? Waits wait after
1 unavailable no, 1 is less than 3 100 ms 200 ms
2 unavailable no, 2 is less than 3 200 ms 400 ms
3 unavailable yes, 3 reaches 3 none

Three sends and two waits, of 100 ms and 200 ms. There is no wait after the last attempt, because the return comes before sleep. Because the check comes after the first send, a call with attempts of 0 still sends once.

The template part changes nothing about this logic. It only means that sleep can be any callable that accepts a duration: the test’s lambda, or the service’s std::function.

Its tests pass lambdas. The wait goes through no interface, no virtual call, and no allocation; the compiler makes one copy of the function for each lambda type. (Sending still goes through the Notifier interface.)

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_retry.cpp
// deliver_with_retry takes its sleeper as a template parameter, so these
// tests pass a lambda directly. Nothing waits, and the wait is not a
// virtual call.
// Busy twice, then (script used up) sent, with 5 attempts allowed: proves the loop stops at
// the first success, after 3 sends, and waited 100 ms then 200 ms in between.
LLD_TEST(a_busy_network_is_retried_until_the_message_goes) {
SpyNotifier notifier({SendResult::unavailable, SendResult::unavailable});
std::vector<std::chrono::milliseconds> waits;
// A lambda: a small unnamed function. `[&waits]` captures the vector by reference, so
// each call appends to this test's `waits`, which outlives the lambda.
const auto record = [&waits](std::chrono::milliseconds wait) { waits.push_back(wait); };
LLD_CHECK(deliver_with_retry(notifier, "+15550100", "hi", 5, record) == SendResult::sent);
LLD_CHECK_EQ(notifier.calls.size(), 3u); // busy, busy, sent
const std::vector<std::chrono::milliseconds> expected{100ms, 200ms};
LLD_CHECK(waits == expected);
}
// Busy for all 4 attempts allowed: proves it gives up with "unavailable" after exactly 4
// sends, and waits only between them (3 times), not after the last one.
LLD_TEST(retrying_stops_after_the_last_attempt_without_a_final_wait) {
SpyNotifier notifier({SendResult::unavailable, SendResult::unavailable,
SendResult::unavailable, SendResult::unavailable});
int wait_count = 0;
// `[&]` captures what the lambda uses (wait_count) by reference. The duration parameter
// has no name: this test counts the waits and ignores their length.
const SendResult result = deliver_with_retry(notifier, "+15550100", "hi", 4,
[&](std::chrono::milliseconds) { ++wait_count; });
LLD_CHECK(result == SendResult::unavailable);
LLD_CHECK_EQ(notifier.calls.size(), 4u);
LLD_CHECK_EQ(wait_count, 3);
}
// Rejected at once: proves there is no second send and no wait, though 5 attempts are allowed.
LLD_TEST(a_rejected_number_is_not_retried) {
SpyNotifier notifier({SendResult::rejected});
int wait_count = 0;
const SendResult result = deliver_with_retry(notifier, "555-0102", "hi", 5,
[&](std::chrono::milliseconds) { ++wait_count; });
LLD_CHECK(result == SendResult::rejected);
LLD_CHECK_EQ(notifier.calls.size(), 1u);
LLD_CHECK_EQ(wait_count, 0);
}

The service, on the other hand, stores its waiting function in a std::function (the Sleeper alias). That is a function seam: the test still passes a lambda, but the service does not have to be a template. If ReminderService were a template on its sleeper, every class that held one would have to name the sleeper’s type, and its code would have to move into the header. A std::function costs an indirect call per wait, and possibly one allocation when it is stored, in the constructor; calling it never allocates. Both are nothing next to sending a text.

The vendor’s library is one function in a header:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

vendor_sms.hpp
// Imagine this header came with an SMS provider's library: a plain
// function, not an interface, and not ours to change. Returns 0 if the
// message was accepted, 1 if the number is invalid, 2 if the network is
// busy; other values are reserved.
// Only a declaration: it says the function exists, not what it does. Which definition the
// program gets is decided when it is linked, which is the link seam on this page.
// It takes C-style strings (pointers to characters ending in a zero byte), not std::string.
namespace vendor {
int sms_send(const char* number, const char* text);
}

The first rule for code like this is do not let it into the service. One small adapter, the only code that includes the vendor’s header, implements Notifier and translates the status codes:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

sms_notifier.hpp
// The adapter from our Notifier port to the vendor's function. It is the
// only code that knows the vendor's status codes. It holds no state: each send is one call
// to the vendor's function.
class SmsNotifier final : public Notifier {
public:
[[nodiscard]] SendResult send(const std::string& phone, const std::string& text) override;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

sms_notifier.cpp
// Sends through the vendor and translates the vendor's number into a SendResult.
SendResult SmsNotifier::send(const std::string& phone, const std::string& text) {
// c_str() gives the C-style string the vendor wants. The pointer is valid while the
// std::string is alive and unchanged, which covers the whole call.
switch (vendor::sms_send(phone.c_str(), text.c_str())) {
case 0: return SendResult::sent;
case 1: return SendResult::rejected;
case 2: return SendResult::unavailable;
default: return SendResult::unavailable; // unknown: assume it may pass later
}
}

The service’s tests never see the adapter; they use the doubles above. But the adapter has logic of its own, the mapping of codes, and an unknown code is a decision someone made: treat it as “try again later”. How can the adapter be tested without sending texts?

SmsNotifier calls a plain function, and there is no object to replace. But the function’s definition is chosen by the linker. The adapter is built into its own library, tst_reminders_sms, which leaves vendor::sms_send undefined. Each executable then supplies a definition: the demo links a console stand-in that prints the message, and the adapter’s test links a fake:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

fake_vendor_sms.cpp
// The same signature as the vendor's function, defined by the test. The
// linker resolves SmsNotifier's call to this definition because the real
// library is not linked into the test executable.
// `status` and `sent` are the fake's globals, defined at the top of this file in an unnamed
// namespace, so no other file can see or clash with them.
namespace vendor {
int sms_send(const char* number, const char* text) {
// Building a Message copies both C strings into std::strings. Keeping the pointers
// instead would be a bug: they point into the caller's strings, which may be gone
// by the time the test reads them.
sent.push_back({number, text});
return status; // whatever the test chose with reset()
}
} // namespace vendor

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

fake_vendor_sms.hpp
// Global, because the vendor function is a free function with no object
// to hold its state. Call reset() at the start of every test.
// reset: forget every recorded message, and make each later sms_send return this status.
void reset(int status_to_return);
// Every message sms_send received since the last reset, oldest first. A reference to the
// fake's own vector, not a copy: later sends add to what it shows.
[[nodiscard]] const std::vector<Message>& messages();
How this code works: how a call reaches the fake
  1. A test calls notifier.send("+15550100", "Hi Asha") on a real SmsNotifier.
  2. SmsNotifier::send calls vendor::sms_send. When sms_notifier.cpp was compiled, the compiler saw only the declaration in vendor_sms.hpp, so it left a note for the linker: “a function named vendor::sms_send with this signature goes here”.
  3. The linker builds the test program from test_sms_notifier.cpp, fake_vendor_sms.cpp, and the libraries. The only definition of vendor::sms_send it finds is the one in fake_vendor_sms.cpp, so the call goes there. The demo program is linked with vendor_sms_console.cpp instead, so the same call prints a line.
  4. The fake copies the number and text into its global list sent and returns the global status.
  5. Back in SmsNotifier::send, the switch turns that number into a SendResult.

reset and messages are how the test talks to the fake, since there is no fake object to call methods on: reset(1) before a send makes it return 1, which the adapter must turn into rejected.

The choice is made in the build, not in the code. This excerpt is from the example’s CMakeLists.txt (it is built and run as part of the example):

add_library(tst_reminders_sms STATIC sms_notifier.cpp)
target_link_libraries(tst_reminders_sms PUBLIC tst_reminders)
lld_add_example(tst_reminders_demo
SOURCES main.cpp vendor_sms_console.cpp EXPECTED_OUTPUT expected_output.txt)
target_link_libraries(tst_reminders_demo PRIVATE tst_reminders_sms)
lld_add_test(tst_reminders_sms_tests
SOURCES tests/test_sms_notifier.cpp tests/fake_vendor_sms.cpp LABELS unit)
target_link_libraries(tst_reminders_sms_tests PRIVATE tst_reminders_sms)

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_sms_notifier.cpp
// These tests use the real SmsNotifier. Its call to vendor::sms_send reaches the fake in
// fake_vendor_sms.cpp, because that is the only definition linked into this test program.
// Status 0 ("accepted"): proves the adapter says sent, and passes the number and text on as
// they were given.
LLD_TEST(the_number_and_text_reach_the_vendor_unchanged) {
fake_vendor::reset(0); // a clean start: no messages recorded, and return 0 from now on
SmsNotifier notifier;
LLD_CHECK(notifier.send("+15550100", "Hi Asha") == SendResult::sent);
LLD_CHECK_EQ(fake_vendor::messages().size(), 1u);
// at(0) checks the index: if no message was recorded, it throws std::out_of_range,
// which the test runner catches and reports, instead of reading memory that is not there.
LLD_CHECK_EQ(fake_vendor::messages().at(0).number, "+15550100");
LLD_CHECK_EQ(fake_vendor::messages().at(0).text, "Hi Asha");
}
// Statuses 1 and 2: proves each maps to its SendResult. The notifier keeps no state, so
// creating it before reset() makes no difference; reset() sets the next status to return.
LLD_TEST(each_vendor_status_maps_to_a_send_result) {
SmsNotifier notifier;
fake_vendor::reset(1);
LLD_CHECK(notifier.send("555", "hi") == SendResult::rejected);
fake_vendor::reset(2);
LLD_CHECK(notifier.send("+15550100", "hi") == SendResult::unavailable);
}
// A status the vendor reserves (7 here): proves the adapter's decision, "unavailable", so
// that the service will try again later rather than give up on the patient.
LLD_TEST(an_unknown_vendor_status_is_treated_as_worth_retrying) {
fake_vendor::reset(7);
SmsNotifier notifier;
LLD_CHECK(notifier.send("+15550100", "hi") == SendResult::unavailable);
}

Link seams need no change to the code under test, which is their whole appeal: they work on code that was never designed to be tested. They also have real costs:

  • Global state. A free function has no object to keep its state, so the fake keeps it in globals, and every test must call reset() first. Forget it, and a test depends on the one before it.
  • One replacement per executable. Every test in the executable gets the same fake. A test that needs the real library must be a separate executable.
  • The build decides, silently. If an executable ends up with two definitions of vendor::sms_send, the result depends on how they are linked: two object files give a “multiple definition” error, but a definition in a static library may simply never be pulled in, unless the library comes first on the link line, or its file is pulled in for some other symbol, and then it is an error again. It is easy to test a different program from the one that ships. Keep the test’s link line short and explicit, as above.
  • Not portable in every detail. Weak symbols, link order, and shared libraries behave differently on different platforms. The approach here, a separate source file in the test executable, is the most portable one.

So the adapter is tested with a link seam, and everything else goes through the adapter’s interface. The link seam is confined to the one file that touches the vendor.

Over-mocking: tests that check how, not what

Section titled “Over-mocking: tests that check how, not what”

A strict, ordered mock, like the one here, checks exactly the calls it was told to expect, in order. That is precise, and it is also a risk: the test now depends on the order of calls, even where nobody required one.

To see it, a scratch program ran the same requirement, “both patients are reminded”, in two styles: one test with a strict, ordered mock, and one with a spy that checks which phones were sent to, in any order. It ran them against the real service, and then against a refactored copy that sends the earliest appointment first, a sensible change that keeps every requirement. Ben was booked first, for 15:00, and Asha second, for 10:00. Against the real service, both tests passed:

2 test(s), 0 failure(s)

Against the refactored copy, built the same way (paths shortened):

doubles.hpp:124: check failed: send to +15550100, expected send to +15550101
doubles.hpp:124: check failed: send to +15550101, expected send to +15550100
2 test(s), 2 failure(s)

The harness counts failed checks, not failed tests: both failures are the mock’s, and the spy test passed. Nothing the clinic asked for was broken. The mock test failed because it had written down one particular order as if it were a requirement. Multiply that by a few hundred tests, and every refactoring means rewriting tests that were never wrong about the behaviour, which teaches people to “fix” tests by copying the new calls into them without thinking.

How to avoid it:

  • Prefer checking state and results. “Both phones received a text” and “the report says 2 sent” survive any refactoring that keeps the behaviour.
  • Prefer fakes and spies to mocks. They let the test choose afterwards what to check, so it can check only what matters.
  • Use a mock when the interaction is the requirement, as with R4: “exactly one message to a bad number”. Then the expectation is the requirement, and a change that breaks it should fail.
  • Expect only what matters. If a mock must be used, do not require an order the requirements do not require, or calls the test is not about.
  • Count your doubles. A test with five mocks is testing a class with five collaborators; the design may be telling you something.

Every seam on this page was a design decision first. The service has ports because it should not know the vendor, the database, or the real time; the tests needed the same thing, and so did the clinic, the day it changes SMS provider. That is the useful meaning of “designing for testability”: code that is hard to test is usually hard to change for the same reasons, and the seams a test needs are often the ones the design needed anyway.

It has limits:

  • Not everything needs a seam. reminder_text is a pure function and RunReport is a value; adding an interface for either would be ceremony, and testing them is already trivial.
  • A seam that exists only for tests is a cost. An interface with one real implementation, introduced just so a test can mock a private helper, adds code and indirection, and the test then knows the class’s insides. Test through the public behaviour instead.
  • Seams belong at boundaries. Time, randomness, files, networks, other processes, and code you do not own. Inside the core, plain functions and values are easier to test than any double.

The demo wires the real pieces together: the adapter, a real sleep, and the console stand-in for the vendor. Only the clock is fixed, so that the output is the same on every run:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Every object is a local of main, created before the service, so all of them outlive
// it (locals are destroyed in reverse order). The service holds references to them.
clinic::MemoryBook book; // fields: id, patient, phone, start (minutes from day 0)
book.book({1, "Asha", "+15550100", 10h + 30min}); // day 0, 10:30
book.book({2, "Ben", "+15550101", 24h + 7h + 45min}); // day 1, 07:45
book.book({3, "Chidi", "555-0102", 11h}); // not a valid number
book.book({4, "Dana", "+15550103", 24h + 9h}); // day 1, 09:00
DemoClock clock; // fixed at 08:00 on day 0 until main changes it
clinic::SmsNotifier notifier; // the real adapter; the demo links the console vendor
// The real waiting function: a lambda with no captures that pauses this thread.
const clinic::Sleeper sleep = [](std::chrono::milliseconds wait) {
std::this_thread::sleep_for(wait);
};
// The service takes its own copy of `sleep` (the parameter is by value); the rest are
// passed by reference.
clinic::ReminderService service(book, notifier, clock, sleep);
Expected output
08:00 run
[sms to +15550100] Hi Asha, your appointment is today at 10:30.
[sms to +15550101] Hi Ben, your appointment is tomorrow at 07:45.
08:00: sent 2, rejected 1, failed 0
08:00 again: sent 0, rejected 0, failed 0
10:00 run
[sms to +15550103] Hi Dana, your appointment is tomorrow at 09:00.
10:00: sent 1, rejected 0, failed 0

Chidi’s number, 555-0102, has no + and country code, so the stand-in rejects it, and the run reports one rejection. At 10:00, Dana’s appointment the next day at 09:00 is within 24 hours, and her reminder goes out; Asha and Ben are not sent a second one.

class clinic::AppointmentBook

interface seam

Member functions

  • virtual std::vector<Appointment> between(Minutes from, Minutes to) const = 0;

class clinic::Notifier

interface seam

Member functions

  • virtual SendResult send(const std::string& phone, const std::string& text) = 0;

class clinic::Clock

interface seam

Member functions

  • virtual Minutes now() const = 0;

class clinic::ReminderService

Data members

  • const AppointmentBook& book_;
  • Notifier& notifier_;
  • const Clock& clock_;
  • Sleeper sleep_; function seam: std::function<void(std::chrono::milliseconds)>
  • int attempts_;
  • std::set<int> reminded_;

Member functions

  • ReminderService(const AppointmentBook& book, Notifier& notifier, const Clock& clock, Sleeper sleep, int attempts = 3);
  • RunReport run(); R1 to R4

class clinic::SmsNotifier

final; the adapter; calls vendor::sms_send, a link seam

Member functions

  • SendResult send(const std::string& phone, const std::string& text) override;

class clinic::MemoryBook

final; fake

Member functions

  • void book(Appointment appointment);

class clinic::testing::ManualClock

final; fake

Member functions

  • void advance(Minutes by);

class clinic::testing::StubNotifier

final; stub

Member functions

  • explicit StubNotifier(SendResult answer);

class clinic::testing::SpyNotifier

final; spy

Member functions

  • std::vector<Call> calls;

class clinic::testing::MockNotifier

final; mock

Member functions

  • void expect_send(std::string phone, std::string text, SendResult answer);
  • void verify() const;
The service's seams, and the doubles the tests put in them

When this approach fits, and when it does not

Section titled “When this approach fits, and when it does not”

Doubles fit code that coordinates: services that take decisions and call out to the world. They fit less well when:

  • The code is mostly the boundary. An SQL query, a file format, or a protocol is only tested by running it against the real thing. A fake database tests nothing about the query.
  • The double is harder than the real thing. If a real, local dependency is fast and deterministic, such as a temporary file or an in-process database, use it. A double is a means, not a goal.
  • The code is a thin wrapper. SmsNotifier is nearly all translation. Its link-seam test is worth having because the translation has a decision in it; a wrapper with no decisions may need only the integration test against the real service.
  • Mocking everything. Tests that list every call break on every refactoring and check nothing the user would notice.
  • Mocking values or pure functions. Use the real ones; they are already deterministic.
  • A fake that drifts from the real implementation. Run the same contract test against both.
  • Doubles of code you do not own. Wrap it, and double the wrapper.
  • Forgetting to reset link-seam state. A global fake makes test order matter unless every test starts with reset().
  • Sleeping in tests. A test that waits for real time is slow and, when the machine is busy, flaky. Make waiting a seam.
  • Seams for tests only. An interface added just so a test can reach a private helper; test through the public behaviour instead.
  • “Also send reminders by e-mail.” Add an EmailNotifier adapter for the same Notifier port, or a second port if e-mail needs different data. The service’s tests do not change; the new adapter gets its own test, at whatever seam its library offers.
  • “Store the reminded appointments, so a restart does not resend.” reminded_ moves behind a port, with a fake for tests and a contract test that both implementations pass. The R1 test “only once” then gains a version that restarts the service between runs.
  • “Remind 2 hours before, as well as the day before.” A rule change, so reminder_text and the window logic change, and their tests with them. The doubles do not.

Exercise: Introduce a seam

The clinic’s login code records each login in an audit file. This function was compiled with both of this site’s compilers, but nothing tests it, and as written, nothing can:

#include <chrono>
#include <fstream>
#include <string>
// Appends one line per login to the audit log, with the time in
// seconds since the clock's epoch.
void record_login(const std::string& user) {
// Reads the current time from the system clock.
const auto now = std::chrono::system_clock::now();
// time_since_epoch() is the time since the clock's starting point; duration_cast turns
// it into whole seconds (dropping any fraction), and count() gives the plain number.
const auto seconds =
std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
// Opens the audit file. std::ios::app means "append": add to the end, never
// overwrite. The file is closed when `log` goes out of scope at the closing brace.
std::ofstream log("/var/log/clinic-audit.log", std::ios::app);
log << seconds << " login " << user << '\n';
}
  1. Name the two collaborators that stop this function being tested, and say why each one is a problem in a test.
  2. Introduce seams for both, choosing the simplest kind of seam for each. Existing callers of record_login(user) must keep working without changes.
  3. Write one test that checks the exact line written.
Show the explained answer

1. The clock: the line contains the current time, so a test cannot know what to expect. The file: the path is fixed, a test may not be allowed to write to it, and tests running at the same time would write into the same file, including into the real audit log.

2. Neither needs an interface. The time is a value, so it can be a parameter. The standard library already has a seam for where text goes: std::ostream, which both a file and a string stream are. The old signature stays, as a thin function that wires in the real file and the real clock. This answer was compiled with both compilers, with the test below, and the test was run and passed:

// The rule, with its two collaborators passed in: where the line goes
// (any std::ostream) and what time it is (a time point).
// std::ostream& accepts any output stream by reference: a file, a string stream, or
// std::cout. The function writes to it but does not own it.
void record_login(std::ostream& log, std::chrono::system_clock::time_point now,
const std::string& user) {
const auto seconds =
std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
log << seconds << " login " << user << '\n';
}
// The old signature, kept for existing callers: it only wires in the
// real file and the real clock.
// Both functions are named record_login (an overload); the compiler picks the one whose
// parameters match the call, so the call below goes to the three-parameter version.
void record_login(const std::string& user) {
std::ofstream log("/var/log/clinic-audit.log", std::ios::app);
// A std::ofstream is a kind of std::ostream, so it can be passed as `log`.
record_login(log, std::chrono::system_clock::now(), user);
}

3.

// Proves the exact line written, for a fixed time and user, with no file involved.
LLD_TEST(a_login_is_recorded_with_its_time) {
std::ostringstream log; // an output stream that collects text in memory; str() reads it
// A fixed moment: 1,700,000,000 seconds after the clock's epoch. The ' marks are digit
// separators, there only to make the number easier to read.
const std::chrono::system_clock::time_point at{std::chrono::seconds{1'700'000'000}};
record_login(log, at, "asha");
LLD_CHECK_EQ(log.str(), "1700000000 login asha\n");
}

Things to notice:

  • Passing the value is simpler than passing a clock. The function needs one time, so it takes one time. A Clock interface would be the right seam for code that reads the time more than once, or at moments the caller cannot predict, like the reminder service.
  • The wiring function is not tested here. It has no logic left; a single integration test, writing to a temporary file, would cover it, as on Testing strategy.
  • What a file cannot do in this design is handled nowhere. If the file cannot be opened, record_login writes nothing and says nothing, exactly like the original. Whether a failed audit write should stop the login is a requirement question, and now there is a place to test the answer: a stream with its failure bit set.
  • A seam is a place where behaviour can change without editing the code. C++ has four common ones: an interface, a function parameter, a template parameter, and the link step. Choose the simplest that fits, and put seams at boundaries: time, randomness, files, networks, and code you do not own.
  • A dummy fills a parameter; a fake really works, simply; a stub gives canned answers; a spy records calls; a mock is told which calls to expect, before the code runs.
  • Prefer real values, then fakes and spies, and check results and state. Use a mock when the interaction itself is the requirement.
  • A strict mock writes down how the code works, and breaks when that changes, even when the behaviour does not.
  • Wrap libraries you do not own in an adapter, double the adapter, and test the adapter on its own, with a link seam if it calls plain functions.
  • Code that is hard to test is usually hard to change; the seams tests need are mostly the ones the design needed anyway.