Skip to content

Testing strategy: unit, integration, and contract tests

Difficulty: Intermediate

Key concepts

  • test level
  • unit test
  • acceptance test
  • contract test
  • integration test
  • end-to-end test
  • test pyramid
  • deterministic test
  • test label
  • What the common levels of testing are, what each one can and cannot catch, and what each one costs.
  • How to turn acceptance criteria into tests, one criterion at a time, so that every promise to the customer has a test that fails when it is broken.
  • How a Contract test checks that every implementation of an interface keeps the interface’s promises, and what it cannot check.
  • Which few things need integration tests with real files, databases, or networks, and why there should be only a few.
  • How to keep a test suite fast and deterministic, and how to run one level at a time.

A delivery company puts banks of lockers in shops and stations. A courier drops a parcel into a free compartment; the customer receives a code and opens the compartment with it. The team writes down what the drop-off feature must do:

# Acceptance criterion
AC1 A parcel goes in the smallest free compartment it fits in; among equal sizes, the lowest-numbered one
AC2 When no free compartment fits, the courier is told “no space”, and nothing is reserved
AC3 A customer’s code opens its compartment once; after that, and for any code never issued, nothing opens
AC4 A code works until 72 hours after the drop-off; after that it opens nothing, and the compartment is released for reuse

Reservations must also survive a restart of the locker’s computer, which happens at night and after power cuts. The example meets the first part fully and the second only in part; the file store section below says why.

The design has three parts: pure rules (choose_compartment, is_expired), a service that applies them in order, and ports for what the service needs from outside: a store for reservations, a clock, and a source of codes. The service never reads the real time or the disk itself.

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

lockers.hpp
// The three compartment sizes. Listed from smallest to largest, so `<`
// compares them by size: Size::small < Size::medium < Size::large. A parcel
// fits in a compartment of its own size or any larger one.
enum class Size { small, medium, large }; // ordered: each fits in the next
// One door in the locker bank: its number (printed on the door) and size.
// Plain data: `{2, Size::medium}` builds one, members in order; `{}` uses the defaults.
struct Compartment {
int number = 0;
Size size = Size::small;
};
// Minutes since a fixed starting point (in the real locker, the system
// clock's epoch). Whole minutes are all the
// rules need, and they keep stored reservations simple.
// `using` gives std::chrono::minutes a shorter name. It is still a type
// that knows its unit: 72 hours converts to it automatically, but a bare
// int must be wrapped, as in Minutes(600) or 600min, to become one.
using Minutes = std::chrono::minutes;
// A code reserved for one compartment until a deadline.
// code: what the customer types; compartment: the door number it opens;
// expires: the minute at which the code stops working (an absolute time,
// not a duration). `expires{}` starts it at zero minutes.
struct Reservation {
std::string code;
int compartment = 0;
Minutes expires{};
// `= default` asks the compiler to write ==, comparing the three
// members in order. Tests use it to check a whole reservation at once.
friend bool operator==(const Reservation&, const Reservation&) = default;
};
// AC4: a code works for 72 hours after the drop-off.
// std::chrono::hours(72) converts to Minutes exactly: 4320 minutes.
// `inline constexpr` makes one compile-time constant that every file
// including this header can share.
inline constexpr Minutes hold_time = std::chrono::hours(72);
// AC1: the smallest free compartment the parcel fits in, and among those
// the lowest number; nullopt if none is free.
// bank: every compartment; occupied: the numbers already reserved;
// parcel: the size to fit. Returns a compartment number, or an empty
// std::optional when nothing free is big enough. Reads its inputs only:
// it changes nothing, so the same inputs always give the same answer.
[[nodiscard]] std::optional<int> choose_compartment(const std::vector<Compartment>& bank,
const std::set<int>& occupied,
Size parcel);
// AC4: a reservation stops working at its deadline, not a minute later.
// `>=` is the whole rule: at exactly `expires` the code is already
// expired. Writing `>` instead would let the code work one minute too
// long. noexcept: comparing two durations cannot throw.
[[nodiscard]] constexpr bool is_expired(const Reservation& r, Minutes now) noexcept {
return now >= r.expires;
}

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

service.hpp
// The service's only way to learn the time. An interface: apart from the
// destructor, its function is pure virtual (marked `= 0`), so it says what
// a clock can do and leaves how to each class that derives from it. The
// real locker passes SystemClock, and tests pass a clock they move by
// hand. The virtual
// destructor lets an object be destroyed safely through a Clock pointer.
class Clock {
public:
virtual ~Clock() = default;
// The current time, in whole minutes. `const`: reading the time does
// not change the clock.
[[nodiscard]] virtual Minutes now() const = 0;
};
// Draws pick-up codes. A real one must be unpredictable; see RandomCodes
// in adapters.hpp.
// next() is not const: drawing a code moves the source on (a random
// generator's state, or a test list's position).
class CodeSource {
public:
virtual ~CodeSource() = default;
[[nodiscard]] virtual std::string next() = 0;
};

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

service.hpp
// Why a drop-off or a pick-up was turned down. These are expected
// outcomes, not programming errors, so they are returned, not thrown.
enum class Refusal { no_space, unknown_code, expired };
// A readable name for a refusal, such as "no space", for printing.
[[nodiscard]] const char* refusal_name(Refusal refusal) noexcept;
// What a successful pick-up gives back: which door to open.
struct Opened {
int compartment = 0;
};
// Each result holds exactly one of two things. std::variant is a box that
// holds one value of one of the listed types: a drop-off gives either the
// new Reservation or the Refusal; a pick-up gives either Opened or the
// Refusal. The caller asks which one with std::get_if (see the idiom
// reference on std::variant).
using DropOffResult = std::variant<Reservation, Refusal>;
using PickUpResult = std::variant<Opened, Refusal>;
// The feature itself: it applies the rules in the right order and keeps
// reservations through the store. It owns its copy of the compartment
// list, and only refers to (does not own) the store, clock, and codes.
class DropOffService {
public:
// The store, clock, and code source must outlive the service.
// The service keeps references to them (the `&` members below), not
// copies, so the tests can look into the same store and move the same
// clock the service uses. The bank is taken by value and moved in.
DropOffService(std::vector<Compartment> bank, ReservationStore& store, const Clock& clock,
CodeSource& codes);
// AC1, AC2: reserve the best compartment for a parcel, or refuse.
// Returns the new Reservation (its code, compartment, and deadline)
// or Refusal::no_space. Throws std::runtime_error if the code source
// keeps repeating codes in use, and passes on anything the store throws.
[[nodiscard]] DropOffResult drop_off(Size parcel);
// AC3, AC4: open the compartment for a valid code, once.
// Returns Opened, or Refusal::unknown_code or Refusal::expired.
[[nodiscard]] PickUpResult pick_up(std::string_view code);
// AC4: free every compartment whose code has expired; returns how many.
// Until this runs, an expired reservation still holds its compartment,
// so a scheduled job must call it, for example every few minutes.
int release_expired();
private:
// A fresh code that no current reservation uses.
[[nodiscard]] std::string unused_code();
std::vector<Compartment> bank_; // owned: the service's own copy
ReservationStore& store_; // not owned: see the constructor comment
const Clock& clock_; // not owned, and only read
CodeSource& codes_; // not owned
};

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

service.cpp
// AC1 and AC2. Works out which compartments are taken, asks the rule for
// the best free one, and only then draws a code and stores the
// reservation. A refusal changes nothing.
DropOffResult DropOffService::drop_off(Size parcel) {
// The store does not keep a list of occupied compartments, so build
// one: every current reservation holds its compartment, expired or not.
std::set<int> occupied;
for (const Reservation& r : store_.all()) occupied.insert(r.compartment);
const std::optional<int> compartment = choose_compartment(bank_, occupied, parcel);
// An empty optional is false: no compartment fits. Returning a Refusal
// where a DropOffResult is expected puts the Refusal in the variant.
if (!compartment) return Refusal::no_space;
// *compartment reads the number out of the optional (safe: it was just
// checked). The deadline is the current time plus 72 hours. The three
// values inside the braces are worked out left to right, so the code
// is drawn first. If unused_code() throws, nothing has been stored.
Reservation reservation{unused_code(), *compartment, clock_.now() + hold_time};
store_.add(reservation); // the store keeps its own copy
return reservation; // the caller gets the code to give to the customer
}
// AC3 and AC4. Finds the code, refuses it if it is unknown or expired,
// and otherwise removes the reservation so the code cannot be used again.
PickUpResult DropOffService::pick_up(std::string_view code) {
// find() returns a copy of the reservation, or an empty optional.
const std::optional<Reservation> found = store_.find(code);
if (!found) return Refusal::unknown_code;
// An expired code is refused but not removed here: its compartment is
// freed later by release_expired().
if (is_expired(*found, clock_.now())) return Refusal::expired;
store_.remove(code); // a code opens its compartment once
// `found` is a copy, so it is still readable after the removal.
return Opened{found->compartment};
}
// AC4. Removes every expired reservation and counts how many went.
int DropOffService::release_expired() {
int released = 0;
// store_.all() returns a vector by value, so the loop walks a copy.
// Removing reservations from the store inside the loop is therefore
// safe: it does not disturb the list being walked.
for (const Reservation& r : store_.all()) {
// `&&` stops early: remove() runs only for an expired reservation,
// and the count goes up only if remove() really found and removed it.
if (is_expired(r, clock_.now()) && store_.remove(r.code)) ++released;
}
return released;
}
// Codes are random, so two may collide; a code in use is never handed
// out twice. Five collisions in a row means the source is broken.
// Each attempt draws a code and keeps it only if no reservation has it.
// Five draws, all in use, end in std::runtime_error instead of looping
// forever.
std::string DropOffService::unused_code() {
for (int attempt = 0; attempt < 5; ++attempt) {
std::string code = codes_.next();
if (!store_.find(code)) return code; // nobody has it: use it
}
throw std::runtime_error("the code source keeps repeating codes in use");
}
How this code works: DropOffService

Each of the three public functions reads the store, decides, and only then changes the store.

  1. drop_off first builds the set of occupied compartment numbers from store_.all(). Every stored reservation counts, even an expired one, because an expired reservation keeps its compartment until release_expired runs. It hands that set to the pure rule choose_compartment. If the rule finds nothing, the function returns Refusal::no_space before drawing a code or touching the store: that is AC2’s “nothing is reserved”. Otherwise it draws an unused code, sets the deadline to now plus 72 hours, stores the reservation, and returns it.
  2. pick_up looks the code up. An unknown code is refused. An expired code is refused too, but it stays in the store; only release_expired frees it. A valid code is removed before the function returns, so the same code finds nothing the second time (AC3’s “once”).
  3. release_expired walks a copy of every reservation (the vector that all() returns) and removes each expired one. Because it walks a copy, removing from the store during the loop is safe.
  4. unused_code draws up to five codes and returns the first one that no reservation has. If all five are in use, it throws, and since drop_off calls it before store_.add, nothing is stored.

Here is the test ac4_after_72_hours_the_code_fails_and_the_compartment_is_released traced step by step. The bank is compartment 1 (small), 2 and 3 (medium), and 4 (large); the clock starts at minute 1000; 72 hours is 4320 minutes.

Step Call Store afterwards Result
1 drop_off(Size::small) AAAAAA in 1, expires at 5320 compartment 1
2 drop_off(Size::small) also BBBBBB in 2, expires at 5320 compartment 2 (1 is taken, so the next size up)
3 clock.advance(72h) unchanged; the time is now 5320
4 pick_up("AAAAAA") unchanged: an expired code is not removed “expired”, because 5320 >= 5320
5 release_expired() empty 2
6 drop_off(Size::small) CCCCCC in 1, expires at 9640 compartment 1

The service does nothing on its own. release_expired frees the compartments of expired codes only when something calls it, so the real locker needs a scheduled job that calls it every few minutes; until then, an expired reservation still holds its compartment.

Every test answers one question: if this were broken, would I find out, and how soon? Tests differ in what they can see, how fast they run, how reliably they give the same answer, and how precisely a failure points at the cause. No single kind is good at all four, so a suite mixes them on purpose. A strategy is the decision about which mix, and it is part of the design: code whose rules are pure functions and whose outside world comes through ports can be tested quickly and precisely; code that reads the clock and the disk itself can be tested only slowly, or not at all.

The names below are common, but teams use them differently. This page means:

Level What runs Catches Misses Cost
Unit One function or class, with plain values Wrong rules, wrong edge cases; points at the exact function Parts that each work but do not fit together Microseconds; no setup
Acceptance The service, with test doubles for its ports A criterion that is not met; wrong order of steps Bugs in the real adapters Microseconds; a small fixture
Contract The same checks against every implementation of one interface An implementation that breaks a written promise Promises nobody wrote into the contract As fast as the slowest implementation
Integration Your code with a real file, database, or network Wrong formats, wrong assumptions about the real thing, lost data Not the place for rule bugs: slow and imprecise there Milliseconds or more; cleanup
End-to-end The whole program, as a user or another system uses it Wiring mistakes: the wrong adapter built, a missing step at start-up Almost every detail; failures point nowhere in particular Slowest; often flaky

“Acceptance” is not quite a level like the others: it names what a test checks, an acceptance criterion, not how much of the program it runs. Many teams check acceptance criteria end to end, through the user interface or the API. This page checks them through the service, with doubles for its ports; tests run that way are often called component, service, or subcutaneous tests. Some teams also call every test that uses more than one class an integration test. The names matter less than knowing, for each test, what is real and what is replaced.

Which code each level of test exercises. Lower levels see less of the program and run faster; only the tests that use FileStore (its contract test, the integration tests, and the demo) touch the real file.
Text description of the diagram

The program has rules (choose_compartment and is_expired), a DropOffService that uses the rules, and two implementations of the ReservationStore interface: MemoryStore and FileStore, which reads and writes the reservations file. Unit tests call only the rules. Acceptance tests call the DropOffService, with a manual clock and a list of codes, and use MemoryStore as its store. One contract test runs against both MemoryStore and FileStore. Integration tests run the DropOffService with the FileStore, so they reach the real file. The demo, end to end, also runs the service with the FileStore.

Diagram source (Mermaid)
flowchart TB
subgraph Program["the locker program"]
  R["rules<br/>choose_compartment, is_expired"]
  S["DropOffService"]
  MS["MemoryStore"]
  FS["FileStore"]
  F[("reservations file")]
  S --> R
  S -->|"ReservationStore"| MS
  S -->|"ReservationStore"| FS
  FS --> F
end
U["unit tests"] --> R
A["acceptance tests<br/>+ manual clock, listed codes"] --> S
A -.->|"uses"| MS
C["one contract test"] --> MS
C --> FS
I["integration tests"] --> S
I --> FS
E["demo, end to end"] --> S
E --> FS

The rules are pure functions: given the same values, they always give the same answer, and they touch nothing outside. That makes them the cheapest code in the program to test, and the place where the edge cases belong.

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

lockers.cpp
// Looks at every compartment once and keeps the best candidate seen so
// far. "Best" means: big enough and free, then the smallest size, then
// the lowest number. It does not rely on the order of `bank`.
std::optional<int> choose_compartment(const std::vector<Compartment>& bank,
const std::set<int>& occupied, Size parcel) {
// A pointer to the best compartment so far, or nullptr while there is
// none yet. It points into `bank`, which outlives this function call,
// so it stays valid; the function returns a copy of the number, never
// the pointer.
const Compartment* best = nullptr;
for (const Compartment& c : bank) {
// Skip what cannot be used: too small for the parcel, or already
// reserved. contains() asks the set "is this number in you?".
if (c.size < parcel || occupied.contains(c.number)) continue;
// Take this one if it is the first usable compartment, or smaller
// than the best so far, or the same size with a lower number.
// `best == nullptr` is tested first, so best->size is read only
// when best points at something.
if (best == nullptr || c.size < best->size ||
(c.size == best->size && c.number < best->number)) {
best = &c; // & takes the address of the element in the bank
}
}
if (best == nullptr) return std::nullopt; // nothing free is big enough
return best->number; // an int converts to std::optional<int> holding it
}
How this code works: choose_compartment

The function makes one pass over the bank and remembers the best usable compartment so far in best, a pointer that starts as nullptr (“none yet”).

  1. A compartment that is too small, or whose number is in occupied, is skipped with continue.
  2. A usable compartment replaces best if there is no best yet, if it is a smaller size, or if it is the same size with a lower number.
  3. After the loop, nullptr means nothing fitted, so the result is an empty optional; otherwise it is the best compartment’s number.

A trace of choose_compartment(bank, {1}, Size::small), with the bank from the tests:

Compartment Usable? Replaces best? best afterwards
1, small no: it is occupied none
2, medium yes: medium holds a small parcel yes: it is the first usable one 2
3, medium yes no: same size, and 3 is not below 2 2
4, large yes no: large is not smaller than medium 2

The result is 2. Because the decision compares sizes and numbers rather than positions, the order of the bank does not matter: with the shuffled bank {3, medium}, {2, medium}, best is 3 after the first compartment and 2 after the second.

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

test_rules.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false, and the test goes on to its next check. They
// come from the site's small test header, lld_test.hpp. The bank used
// here is {1 small, 2 medium, 3 medium, 4 large}, defined above.
// `{}` as the second argument is an empty set: nothing is occupied.
// Comparing a std::optional<int> with 1 is true only if it holds 1.
// With everything free, each size gets the first compartment of exactly
// its own size.
LLD_TEST(a_parcel_gets_the_smallest_size_it_fits) {
LLD_CHECK(choose_compartment(bank, {}, Size::small) == 1);
LLD_CHECK(choose_compartment(bank, {}, Size::medium) == 2);
LLD_CHECK(choose_compartment(bank, {}, Size::large) == 4);
}
// With 1 taken, the next best is medium compartment 2; with 1, 2, and 3
// taken, only the large one is left, and a small parcel may use it.
LLD_TEST(a_small_parcel_moves_up_a_size_when_the_small_ones_are_taken) {
LLD_CHECK(choose_compartment(bank, {1}, Size::small) == 2);
LLD_CHECK(choose_compartment(bank, {1, 2, 3}, Size::small) == 4);
}
// Free compartments that are too small do not count: with 4 taken, a
// large parcel gets nothing, even though 1, 2, and 3 are free.
LLD_TEST(a_parcel_never_goes_in_a_compartment_too_small_for_it) {
LLD_CHECK(choose_compartment(bank, {4}, Size::large) == std::nullopt);
LLD_CHECK(choose_compartment(bank, {1, 2, 3, 4}, Size::small) == std::nullopt);
}
// Compartment 3 comes first in this list, but 2 must still win: the rule
// is the lowest number, not the first one found.
LLD_TEST(among_equal_sizes_the_lowest_number_wins_whatever_the_order) {
const std::vector<Compartment> shuffled{{3, Size::medium}, {2, Size::medium}};
LLD_CHECK(choose_compartment(shuffled, {}, Size::medium) == 2);
}
// Both sides of the deadline, and the deadline itself. 1000min is a
// std::chrono::minutes value of 1000, written with a literal suffix from
// std::chrono_literals (the `using namespace` at the top of the file).
LLD_TEST(a_code_expires_exactly_at_its_deadline) {
const Reservation r{"ABC234", 1, 1000min};
LLD_CHECK(!is_expired(r, 999min));
LLD_CHECK(is_expired(r, 1000min));
LLD_CHECK(is_expired(r, 1001min));
}
// static_assert is checked by the compiler, not when the tests run: if
// hold_time stops being 72 hours, this file does not compile.
static_assert(lockers::hold_time == 72h);
  • Each test names the rule it checks. When one fails, its name says what broke, before anyone reads the code.
  • Boundaries are tested on both sides. The expiry test checks a minute before the deadline, the deadline itself, and a minute after: “at 72 hours” is exactly where an off-by-one bug would hide, with > written for >=.
  • Input order is varied on purpose. The shuffled bank checks that “lowest number” does not secretly mean “first in the list”.
  • A static_assert checks a constant at compile time. If someone changes the hold time, the test file stops compiling, and the change has to be made on purpose. The AC4 acceptance tests would catch the change too, later and less directly; the static_assert is kept because it costs nothing and sits next to the rule it guards.

Acceptance tests check the promises in the table above, through the service, which is the code that keeps them. They replace the three ports with simple stand-ins, called test doubles: an in-memory store, a clock that moves only when the test says so, and a code source that hands out a known list. Test doubles and seams covers the kinds of doubles in detail.

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

support.hpp
// A clock that moves only when the test says so.
// It starts at the time given and stays there until advance() is called,
// so a test can jump 72 hours ahead in an instant and knows the exact
// time the service will read.
class ManualClock final : public Clock {
public:
explicit ManualClock(Minutes start) : now_(start) {}
[[nodiscard]] Minutes now() const override { return now_; }
void advance(Minutes by) { now_ += by; } // move the time forward by `by`
private:
Minutes now_;
};
// Hands out the codes it was given, in order.
// Given {"AAAAAA", "BBBBBB"}, the first next() returns "AAAAAA" and the
// second "BBBBBB". Asking for more than it was given throws
// std::logic_error: that is a mistake in the test, not in the service.
class ListCodes final : public CodeSource {
public:
// Takes the list by value and moves it in: no second copy is made.
explicit ListCodes(std::vector<std::string> codes) : codes_(std::move(codes)) {}
[[nodiscard]] std::string next() override {
if (used_ == codes_.size()) throw std::logic_error("ListCodes: out of codes");
// used_++ reads the current position, then moves on by one: return
// the next unused code, and remember it is now used.
return codes_[used_++];
}
private:
std::vector<std::string> codes_;
std::size_t used_ = 0; // how many codes have been handed out so far
};

A small fixture builds everything a test needs, fresh for each test, so no test can leave state behind for the next:

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

test_acceptance.cpp
// Everything a test needs, built fresh for each one.
// Members are built in the order they are written, so the store, clock,
// and codes exist before the service that refers to them, and are
// destroyed after it. A test writes `Locker locker;` and reaches each
// part by name: locker.service to act, locker.store and locker.clock to
// look and to move time. The clock starts at minute 1000; the codes are
// handed out in order, so the first drop-off always gets "AAAAAA".
struct Locker {
MemoryStore store;
ManualClock clock{1000min};
ListCodes codes{{"AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD", "EEEEEE"}};
DropOffService service{bank, store, clock, codes}; // copies the bank
};

Then each criterion becomes one or more tests. The method: read the criterion, find each separate promise in it, and for each one write the smallest scenario where breaking the promise would change what the customer sees.

Criterion Promises in it Tests
AC1 smallest that fits; lowest number among equals ac1_each_parcel_gets_the_smallest_free_compartment_it_fits (the bank here is in order, so “lowest number” versus “first in the list” is left to the shuffled unit test)
AC2 “no space” is reported; nothing is reserved ac2_when_nothing_fits_the_courier_is_told_and_nothing_is_reserved
AC3 opens once; never-issued codes open nothing ac3_a_code_opens_its_compartment_once, ac3_a_code_that_was_never_issued_opens_nothing
AC4 still works just before 72 hours; fails at 72; released ac4_a_code_still_works_a_minute_before_72_hours, ac4_after_72_hours_the_code_fails_and_the_compartment_is_released

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

test_acceptance.cpp
// LLD_CHECK_EQ(actual, expected) fails if the two are not equal, and then
// prints both values, which is why outcome() turns each result into
// readable text such as "compartment 1". Each drop-off below reserves a
// compartment, so the next small parcel finds compartment 1 already taken.
LLD_TEST(ac1_each_parcel_gets_the_smallest_free_compartment_it_fits) {
Locker locker;
LLD_CHECK_EQ(outcome(locker.service.drop_off(Size::small)), "compartment 1");
LLD_CHECK_EQ(outcome(locker.service.drop_off(Size::small)), "compartment 2");
LLD_CHECK_EQ(outcome(locker.service.drop_off(Size::large)), "compartment 4");
}
// Fill the only large compartment, then ask for another: the reply is
// "no space", and the store still holds just the first reservation.
LLD_TEST(ac2_when_nothing_fits_the_courier_is_told_and_nothing_is_reserved) {
Locker locker;
// drop_off is [[nodiscard]]; static_cast<void> says "result not needed
// here" on purpose. This takes compartment 4.
static_cast<void>(locker.service.drop_off(Size::large));
LLD_CHECK_EQ(outcome(locker.service.drop_off(Size::large)), "no space");
LLD_CHECK_EQ(locker.store.all().size(), std::size_t{1});
}
// The first pick-up opens the door; the second finds no such code, and
// the compartment can be reserved again.
LLD_TEST(ac3_a_code_opens_its_compartment_once) {
Locker locker;
static_cast<void>(locker.service.drop_off(Size::medium)); // AAAAAA, compartment 2
LLD_CHECK_EQ(outcome(locker.service.pick_up("AAAAAA")), "opens 2");
LLD_CHECK_EQ(outcome(locker.service.pick_up("AAAAAA")), "unknown code");
LLD_CHECK_EQ(outcome(locker.service.drop_off(Size::medium)), "compartment 2"); // free again
}
// A made-up code is refused, and the real reservation is left alone.
LLD_TEST(ac3_a_code_that_was_never_issued_opens_nothing) {
Locker locker;
static_cast<void>(locker.service.drop_off(Size::small));
LLD_CHECK_EQ(outcome(locker.service.pick_up("ZZZZZZ")), "unknown code");
LLD_CHECK_EQ(locker.store.all().size(), std::size_t{1});
}
// The deadline is minute 1000 + 4320 = 5320; this picks up at 5319.
LLD_TEST(ac4_a_code_still_works_a_minute_before_72_hours) {
Locker locker;
static_cast<void>(locker.service.drop_off(Size::small)); // AAAAAA, compartment 1
locker.clock.advance(72h - 1min);
LLD_CHECK_EQ(outcome(locker.service.pick_up("AAAAAA")), "opens 1");
}
// At exactly 72 hours both codes have expired. The refused pick-up does
// not free anything; release_expired() frees both compartments, and a new
// small parcel gets compartment 1 again.
LLD_TEST(ac4_after_72_hours_the_code_fails_and_the_compartment_is_released) {
Locker locker;
static_cast<void>(locker.service.drop_off(Size::small)); // compartment 1, AAAAAA
static_cast<void>(locker.service.drop_off(Size::small)); // compartment 2, BBBBBB
locker.clock.advance(72h);
LLD_CHECK_EQ(outcome(locker.service.pick_up("AAAAAA")), "expired");
LLD_CHECK_EQ(locker.service.release_expired(), 2);
LLD_CHECK(locker.store.all().empty());
LLD_CHECK_EQ(outcome(locker.service.drop_off(Size::small)), "compartment 1");
}
  • The names start with the criterion. That makes the table above, and the traceability table, easy to keep true: search for ac4_ to find every test of AC4.
  • “Nothing is reserved” is checked, not assumed. AC2 has two promises. A test that checked only the reply would pass for a service that reserved a compartment and then said “no space”.
  • Time is controlled. The manual clock moves 72 hours in a microsecond. A test that used the real clock could not check AC4 at all.
  • Codes are known. Because the list is fixed, a test can pick up "AAAAAA"; with random codes, the test would have to fish the code out of the result first, and could never test a collision.

The design also made a promise the criteria did not ask for: a code that is in use is never handed out twice. It needs tests of its own, and the listed codes make the rare case, a collision, easy to set up:

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

test_acceptance.cpp
// Not in the acceptance criteria, but the design made a promise: a code
// in use is never issued twice.
// The list repeats "AAAAAA" on purpose. The second drop-off draws it,
// finds it in use, and draws again, getting "BBBBBB". std::get reads the
// Reservation out of the variant; it would throw std::bad_variant_access
// if the result were a Refusal instead, and the test runner counts an
// exception that escapes a test as a failure.
LLD_TEST(a_code_already_in_use_is_skipped) {
MemoryStore store;
ManualClock clock{0min};
ListCodes codes{{"AAAAAA", "AAAAAA", "BBBBBB"}};
DropOffService service{bank, store, clock, codes};
static_cast<void>(service.drop_off(Size::small));
const auto second = service.drop_off(Size::small);
LLD_CHECK_EQ(std::get<lockers::Reservation>(second).code, std::string("BBBBBB"));
}
// Six copies of one code: the first drop-off uses one, and the second
// draws the other five, all in use, so it gives up with
// std::runtime_error. LLD_CHECK_THROWS(expression, type) fails unless the
// expression throws that type. The last check proves the failed drop-off
// stored nothing.
LLD_TEST(a_code_source_that_only_repeats_is_an_error_and_reserves_nothing) {
MemoryStore store;
ManualClock clock{0min};
ListCodes codes{{"AAAAAA", "AAAAAA", "AAAAAA", "AAAAAA", "AAAAAA", "AAAAAA"}};
DropOffService service{bank, store, clock, codes};
static_cast<void>(service.drop_off(Size::small));
LLD_CHECK_THROWS(service.drop_off(Size::small), std::runtime_error);
LLD_CHECK_EQ(store.all().size(), std::size_t{1});
}

Contract tests: one set of promises, every implementation

Section titled “Contract tests: one set of promises, every implementation”

The store is an interface with two implementations: MemoryStore, used by the acceptance tests, and FileStore, used by the real locker. The acceptance tests are only worth something if the two behave the same way. The interface’s comments say what “the same” means:

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

store.hpp
// Thrown by add() when the code, or the compartment, is already reserved.
// A type of its own, so a caller or a test can catch exactly this error.
// The `using` line borrows runtime_error's constructors, so
// AlreadyReserved("message") works with no constructor written here.
class AlreadyReserved : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
// The storage port: what the service needs from any place that keeps
// reservations. An interface, so the service works with MemoryStore in
// tests and FileStore in the real locker without knowing which it has.
// The comments on each function are the contract every store must keep.
// Codes are passed as std::string_view: a read-only view of the
// caller's characters, so no copy is made just to look a code up.
class ReservationStore {
public:
// Virtual, so a store owned through a ReservationStore pointer (as the
// contract tests do with std::unique_ptr) is destroyed correctly.
virtual ~ReservationStore() = default;
// Keeps the reservation. Throws AlreadyReserved, and changes nothing,
// if its code or its compartment is already in use. Throws
// std::invalid_argument, and changes nothing, if the code is empty or
// contains whitespace. A removed reservation's code and compartment
// can be used again.
virtual void add(const Reservation& reservation) = 0;
// The reservation with exactly this code, if there is one.
// Returns a copy inside std::optional, or an empty optional.
[[nodiscard]] virtual std::optional<Reservation> find(std::string_view code) const = 0;
// Removes the reservation with this code; false if there was none.
virtual bool remove(std::string_view code) = 0;
// Every reservation, in compartment order.
// Returned by value: the caller gets its own vector, which later
// changes to the store do not affect.
[[nodiscard]] virtual std::vector<Reservation> all() const = 0;
};

The promise about empty codes and whitespace comes from the file store: it writes one reservation per line, with spaces between the fields, so a code with a space in it could be saved but never loaded again. The rule could have gone into FileStore alone, but then the two stores would accept different codes, and code that worked with one could fail with the other. Putting it in the contract keeps them substitutable.

A contract test turns those comments into checks, written once, and runs them against every implementation. Here it is a function that takes a factory, so each check can start with a fresh, empty store:

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

store_contract.hpp
using StoreFactory = std::function<std::unique_ptr<ReservationStore>()>; // makes a new store
inline void check_store_contract(const StoreFactory& fresh) { // fresh: called once per block
using namespace std::chrono_literals;
const Reservation a{"ABC234", 2, 600min}; // code, compartment, deadline
const Reservation b{"XYZ789", 1, 900min};
{ // An empty store has nothing to find or remove.
const auto store = fresh(); // unique_ptr: freed at the `}`
LLD_CHECK(store->all().empty());
LLD_CHECK(!store->find("ABC234"));
LLD_CHECK(!store->remove("ABC234"));
}
{ // What is added can be found, exactly as it was added.
const auto store = fresh();
store->add(a);
LLD_CHECK(store->find("ABC234") == a); // true only if found and equal
}
{ // Codes match exactly: no prefixes, no case folding.
const auto store = fresh();
store->add(a);
LLD_CHECK(!store->find("ABC23"));
LLD_CHECK(!store->find("abc234"));
}
{ // A second reservation for a code in use is refused, and changes nothing.
const auto store = fresh();
store->add(a);
LLD_CHECK_THROWS(store->add({"ABC234", 3, 999min}), AlreadyReserved); // same code
LLD_CHECK(store->find("ABC234") == a);
LLD_CHECK_EQ(store->all().size(), std::size_t{1});
}
{ // So is a second reservation for a compartment in use.
const auto store = fresh();
store->add(a);
LLD_CHECK_THROWS(store->add({"NEW567", 2, 999min}), AlreadyReserved); // same compartment
LLD_CHECK(!store->find("NEW567"));
LLD_CHECK(store->find("ABC234") == a);
LLD_CHECK_EQ(store->all().size(), std::size_t{1});
}
{ // A code that could not be stored as one word is refused.
const auto store = fresh();
LLD_CHECK_THROWS(store->add({"", 1, 600min}), std::invalid_argument); // empty code
LLD_CHECK_THROWS(store->add({"AB CD", 1, 600min}), std::invalid_argument); // has a space
LLD_CHECK(store->all().empty());
}
{ // A reservation is removed once; the second attempt finds nothing.
const auto store = fresh();
store->add(a);
LLD_CHECK(store->remove("ABC234"));
LLD_CHECK(!store->remove("ABC234"));
LLD_CHECK(!store->find("ABC234"));
}
{ // Once removed, the code and the compartment can be used again.
const auto store = fresh();
store->add(a);
LLD_CHECK(store->remove("ABC234"));
const Reservation same_compartment{"NEW567", 2, 999min};
store->add(same_compartment);
store->add({"ABC234", 3, 999min}); // the old code, now free
LLD_CHECK(store->find("NEW567") == same_compartment);
LLD_CHECK_EQ(store->all().size(), std::size_t{2});
}
{ // all() is in compartment order, whatever order things were added in.
const auto store = fresh();
store->add(a);
store->add(b);
const std::vector<Reservation> everything = store->all(); // its own vector, by value
LLD_CHECK_EQ(everything.size(), std::size_t{2});
LLD_CHECK(everything.at(0) == b);
LLD_CHECK(everything.at(1) == a);
}
}
How this code works: check_store_contract
  1. The factory. StoreFactory is a std::function that can hold any function, including a lambda, that takes nothing and returns a std::unique_ptr<ReservationStore>: a new, empty store, owned by whoever calls it. The contract does not know or care which kind of store it gets; it uses only the interface.
  2. Two sample reservations. a is code ABC234 in compartment 2, expiring at minute 600; b is code XYZ789 in compartment 1, expiring at minute 900. Their compartments are in the opposite order to their codes on purpose, for the last block.
  3. One block per promise. Each pair of braces starts with fresh(), so it gets its own empty store, and ends with }, where the unique_ptr deletes that store. No block can see what an earlier block did. store-> calls a function through the pointer.
  4. “Changes nothing” is checked, not assumed. After each refused add, the block checks that the store still holds exactly what it held before.
  5. The last block adds a then b and expects all() to return b first, because b has the lower compartment number. A store that returned reservations in code order, or in the order they were added, would return a first and fail both of the final checks.

find returns a std::optional<Reservation>, and store->find(...) == a is true only if the optional holds a reservation equal to a, using the == that Reservation asked the compiler to write.

Each implementation then needs only a few lines:

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

test_memory_store.cpp
// The factory is a lambda, `[] { ... }`, a small unnamed function written
// in place. It captures nothing and returns a new, empty MemoryStore each
// time it is called. std::make_unique<MemoryStore>() returns a
// std::unique_ptr<MemoryStore>, which converts to the
// std::unique_ptr<ReservationStore> that a StoreFactory must return.
LLD_TEST(memory_store_keeps_the_store_contract) {
lockers::testing::check_store_contract([] { return std::make_unique<lockers::MemoryStore>(); });
}

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

test_file_store.cpp
// Same contract, but each fresh store needs its own new file. `[&files]`
// lets the lambda use the `files` vector by reference, so each call adds
// a TempFile to it. The vector lives until the end of the test, after
// every store, so each file is removed only when all the checks are done.
// TempFile cannot be copied or moved, so the vector holds unique_ptrs to
// TempFiles instead of TempFiles themselves.
LLD_TEST(file_store_keeps_the_store_contract) {
std::vector<std::unique_ptr<TempFile>> files; // each store gets a new file
lockers::testing::check_store_contract([&files] {
files.push_back(std::make_unique<TempFile>());
// files.back() is the TempFile just added. FileStore copies the
// path, and no file exists yet, so the store starts empty.
return std::make_unique<FileStore>(files.back()->path());
});
}

To see the contract test catch something, it was run in a scratch program against a third store, written carelessly: it checks for duplicate codes but not for a compartment that is already taken, and returns reservations in code order. It compiled without warnings, and it ran like this (paths shortened):

store_contract.hpp:52: check failed: store->add({"NEW567", 2, 999min}) throws AlreadyReserved
store_contract.hpp:53: check failed: !store->find("NEW567")
actual: 2
expected: 1
store_contract.hpp:55: check failed: store->all().size() == std::size_t{1}
store_contract.hpp:86: check failed: everything.at(0) == b
store_contract.hpp:87: check failed: everything.at(1) == a
1 test(s), 5 failure(s)

Both mistakes were found, and neither would have been found by the acceptance tests, which never use that store. Two things are worth noticing:

  • The failure points at the contract, not at the store. The line numbers are in store_contract.hpp; the test’s name, lazy_store_keeps_the_store_contract in the scratch program, says which implementation failed. Give each implementation’s test a name that says which one it is.
  • A contract test checks a sample of the Liskov substitution principle. Code that uses a ReservationStore relies on these promises; an implementation that breaks one is not substitutable, whatever it inherits from. Like any test, it can show that an implementation is not substitutable, never prove that one is.
  • A contract is only as good as the promises written into it. Without the block that removes a reservation and adds another for the same compartment, a store that never freed a compartment once used would pass every other check, and the service’s “released for reuse” would silently break. When a bug slips past the contract test, add the missing promise to the contract, not only a test to one store.

A contract test checks only what is in the contract. “Survives a restart” is not a promise of ReservationStore, because MemoryStore does not keep it. The file store states its own promises, and their limits:

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

store.hpp
// Keeps reservations in a text file, one per line, so they survive a
// restart. Each change rewrites the file: a temporary file is written
// and then renamed over the old one, so if the program crashes, the
// file is either the old one or the new one. That is not enough for a
// power cut: the data must also be flushed to the disk (fsync on POSIX)
// before and after the rename, which standard C++ cannot do and this
// example does not. Throws std::runtime_error if the file cannot be
// read or written, or if a line in it is malformed.
// `final`: no class may derive from FileStore.
class FileStore final : public ReservationStore {
public:
// Opens the store kept in `path` and reads it all into memory. A file
// that does not exist yet means an empty store (a new locker). Throws
// std::runtime_error if the file exists but cannot be read, or if a
// line in it is malformed. `explicit`: a path does not silently turn
// into a FileStore.
explicit FileStore(std::filesystem::path path);
void add(const Reservation& reservation) override;
[[nodiscard]] std::optional<Reservation> find(std::string_view code) const override;
bool remove(std::string_view code) override;
[[nodiscard]] std::vector<Reservation> all() const override;
private:
// Declared before cache_, so it is set first: the constructor uses
// path_ to load cache_.
std::filesystem::path path_;
// Reads (find, all) answer from this copy in memory; changes update it
// and rewrite the file. It also does
// the rule checks, so both stores refuse exactly the same things.
MemoryStore cache_; // the file's contents, loaded once
};

Its own tests check those promises:

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

test_file_store.cpp
// What only a file store promises, so only its own tests check it.
// TempFile (from tests/support.hpp) picks a unique path and removes the
// file when the test ends, even if a check fails.
// Write through one FileStore, let it be destroyed, then open a second
// one on the same file: it must hold exactly what was left, the one
// reservation that was not removed.
LLD_TEST(reservations_survive_reopening_the_file) {
const TempFile file;
{ // the first store exists only inside these braces
FileStore store(file.path());
store.add({"ABC234", 2, 600min});
store.add({"XYZ789", 1, 900min});
store.remove("XYZ789");
} // the first store is destroyed here; only the file remains
const FileStore reopened(file.path());
LLD_CHECK_EQ(reopened.all().size(), std::size_t{1});
const Reservation expected{"ABC234", 2, 600min};
LLD_CHECK(reopened.find("ABC234") == expected);
}
// A good line followed by a bad one: opening the store must throw rather
// than quietly keep the first reservation and drop the rest.
LLD_TEST(a_malformed_file_is_refused_not_half_loaded) {
const TempFile file;
// A temporary std::ofstream: it opens the file, writes the two lines,
// and closes the file at the end of this statement.
std::ofstream(file.path()) << "ABC234 2 600\nthis is not a reservation\n";
LLD_CHECK_THROWS(FileStore{file.path()}, std::runtime_error);
}
// Make every save fail, then check that neither a refused add nor a
// refused remove changed the store in memory or the file on disk.
LLD_TEST(a_failed_save_changes_neither_the_file_nor_the_store) {
const TempFile file;
FileStore store(file.path());
store.add({"ABC234", 2, 600min});
// A directory where the temporary file should go makes the next save fail.
// std::filesystem::path(file.path()) makes a copy of the path, and
// `+= ".tmp"` adds the suffix to that copy, not to the TempFile.
std::filesystem::create_directory(std::filesystem::path(file.path()) += ".tmp");
LLD_CHECK_THROWS(store.add({"XYZ789", 1, 900min}), std::runtime_error);
LLD_CHECK(!store.find("XYZ789"));
LLD_CHECK_THROWS(store.remove("ABC234"), std::runtime_error);
LLD_CHECK(store.find("ABC234").has_value()); // the failed remove kept it
// A second store, opened on the file, sees only the first reservation.
LLD_CHECK_EQ(FileStore(file.path()).all().size(), std::size_t{1});
}

The last test makes a save fail on purpose: a directory with the temporary file’s name means the file cannot be written. It then checks the file store’s strongest promise, that a failed save changes nothing, as Exception safety calls the strong guarantee. The store achieves it by changing a copy, saving it, and only then keeping it:

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

store.cpp
// The parameter is moved into path_, and then path_ (not the moved-from
// parameter) is passed to load(), which reads the file into a MemoryStore.
// This order is safe because path_ is declared, and so set, before cache_.
FileStore::FileStore(std::filesystem::path path) : path_(std::move(path)), cache_(load(path_)) {}
// Each change is made to a copy, saved, and only then kept, so a failed
// save leaves both the file and this object as they were.
// Step by step: copy the current contents; add to the copy (which may
// throw AlreadyReserved or std::invalid_argument); save the copy, through
// a temporary file (which may throw); only if both worked, move the
// copy into cache_. A throw at any step skips the steps after it.
void FileStore::add(const Reservation& reservation) {
MemoryStore next = cache_; // a full copy of every reservation
next.add(reservation);
save(path_, next);
cache_ = std::move(next); // keep the new contents; `next` is not used again
}
// Reading never touches the file: the copy in memory is up to date.
std::optional<Reservation> FileStore::find(std::string_view code) const { return cache_.find(code); }
// The same copy, change, save, keep steps as add().
bool FileStore::remove(std::string_view code) {
MemoryStore next = cache_;
if (!next.remove(code)) return false; // no such code: nothing to save
save(path_, next);
cache_ = std::move(next);
return true;
}
std::vector<Reservation> FileStore::all() const { return cache_.all(); }
How this code works: FileStore

Construction. path_ is set first, from the moved-in parameter, and cache_ is then filled by load(path_), which reads every line of the file into a MemoryStore. This works only because path_ is declared before cache_ in the class: members are always set in the order they are declared, whatever order the initialiser list uses. If loading throws, no FileStore is made at all.

Every change follows four steps:

  1. Copy: next is a complete copy of cache_.
  2. Change the copy. MemoryStore::add checks the contract’s rules, so a bad reservation throws here, before anything is written.
  3. Save the copy to the file. This may throw.
  4. Keep the copy: cache_ = std::move(next).

If step 2 or 3 throws, step 4 never runs, and next is simply thrown away when the function exits. cache_ was never touched, and neither was the file: the rename that replaces it is the last thing a save does, so a save that throws has not reached it.

A trace of the test a_failed_save_changes_neither_the_file_nor_the_store:

Step What happens cache_ File
1 add({"ABC234", 2, 600min}) saves normally ABC234 ABC234
2 the test makes a directory with the temporary file’s name ABC234 ABC234
3 add({"XYZ789", 1, 900min}): the copy holds both, the save cannot open the temporary file and throws ABC234 ABC234
4 remove("ABC234"): the copy is empty, the save throws again ABC234 ABC234
5 a new FileStore reads the file one reservation

The price is a full copy of every reservation, and a rewrite of the whole file, for each change. That is cheap for one bank of lockers, but the cost grows with the number of reservations.

Integration tests: only what needs the real thing

Section titled “Integration tests: only what needs the real thing”

The file store’s own tests above are already integration tests: they use a real file in the temporary directory. One more checks what no other test can: that the service and the file store, together, keep a reservation across a restart.

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

test_restart.cpp
// The bank here has two compartments: 1 small and 2 medium. The file,
// clock, and codes are made outside the braces, so they last across the
// "restart"; the store and service inside the braces do not.
LLD_TEST(a_parcel_dropped_off_before_a_restart_can_be_picked_up_after_it) {
const TempFile file;
ManualClock clock{1000min};
ListCodes codes{{"AAAAAA", "BBBBBB", "CCCCCC"}};
{ // the locker before the restart
FileStore store(file.path());
DropOffService service(bank, store, clock, codes);
static_cast<void>(service.drop_off(Size::small)); // AAAAAA in 1
static_cast<void>(service.drop_off(Size::medium)); // BBBBBB in 2
} // the locker restarts
// A new store reads the file back, and a new service uses it.
FileStore store(file.path());
DropOffService service(bank, store, clock, codes);
LLD_CHECK_EQ(outcome(service.drop_off(Size::small)), "no space"); // both still taken
LLD_CHECK_EQ(outcome(service.pick_up("BBBBBB")), "opens 2");
clock.advance(72h); // minute 5320: AAAAAA's deadline, so it has expired
LLD_CHECK_EQ(service.release_expired(), 1); // only AAAAAA was left to release
// Read the file once more, with a third store: the release was saved.
LLD_CHECK(FileStore(file.path()).all().empty());
}

A “restart” here means closing the file store and opening the file again. That shows the format and the loading work, but it cannot simulate a power cut, where the operating system may not yet have written the data to the disk. As the FileStore comment above says, surviving that needs fsync (or the platform’s equivalent) on the file and its directory, which standard C++ does not provide and this example does not do. Testing it needs a machine whose power can be cut, or a file system that can simulate it; that is rare, and it is a good reason to keep durability in a well-tested database instead.

Integration tests are worth having and worth keeping few:

  • They are slower. Each one here writes files; one that started a database or a server would take seconds.
  • They need cleanup. TempFile, in tests/support.hpp, picks a unique name and removes the file when the test ends, even if a check fails, so tests cannot see each other’s files, or a file left by yesterday’s run.
  • Their failures are imprecise. “The parcel cannot be picked up after a restart” could be the file format, the loading, the service, or the clock. If the unit and contract tests are thorough, an integration failure usually means the parts were connected wrongly, which is the one thing only this level can show.

The rule of thumb: test each rule once, at the lowest level that can see it, and use integration tests for how the parts meet.

The demo builds the program the way the real locker would, with the system clock, random codes, and a file store, and runs a short day:

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

main.cpp
// The composition root: the one place that picks the real parts. Four
// compartments: one small, two medium, one large.
const std::vector<lockers::Compartment> bank{
{1, Size::small}, {2, Size::medium}, {3, Size::medium}, {4, Size::large}};
// A file name in the temporary directory, with a random number in it,
// so each run starts with no file: an empty locker.
const std::filesystem::path file = demo_file();
// The production clock and code source. They are created here, before
// any store or service, so they outlive every service that refers to
// them, as DropOffService requires.
lockers::SystemClock clock;
lockers::RandomCodes codes;

The real clock and code source are deliberately thin, so there is almost nothing in them left untested. The code source has one promise that no test here checks: the codes must be unpredictable, because a code is all that stands between a stranger and the parcel. Its comment says what that means for a real locker:

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

adapters.hpp
// The real clock. now() reads the computer's clock, measures the time
// since its epoch (its fixed starting point), and rounds that down to
// whole minutes with std::chrono::floor, so 10:41:59 counts as 10:41.
class SystemClock final : public Clock {
public:
[[nodiscard]] Minutes now() const override {
return std::chrono::floor<Minutes>(std::chrono::system_clock::now().time_since_epoch());
}
};
// Six characters from 32 that are hard to confuse (no 0/O, no 1/I).
// The standard does not promise that std::random_device is unpredictable;
// a real locker must use a source that is, because the code is all that
// stands between a stranger and the parcel.
class RandomCodes final : public CodeSource {
public:
// Builds a code one character at a time: six times, pick a random
// position in the alphabet and append the character found there.
[[nodiscard]] std::string next() override {
// The 32 allowed characters, written once for the whole program.
static constexpr std::string_view alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
// Turns raw random numbers into positions 0 to 31, each equally
// likely. Both ends of the range are included, hence size() - 1.
std::uniform_int_distribution<std::size_t> pick(0, alphabet.size() - 1);
std::string code;
for (int i = 0; i < 6; ++i) code += alphabet[pick(device_)];
return code;
}
private:
// The source of raw random numbers. Drawing from it changes its
// state, which is why next() cannot be const.
std::random_device device_;
};
Expected output
drop off small: compartment 1
drop off small: compartment 2
drop off large: compartment 4
drop off medium: compartment 3
drop off small: no space
-- the locker restarts
reservations kept: 4
pick up with the first code: compartment 1 opens
pick up with the first code again: unknown code
pick up with a made-up code: unknown code
drop off small: compartment 1

The build runs the demo and compares its output with the recorded expected output, so it is a test too: a smoke test that the real parts start and work together. It shows its limits as well. The codes and times change on every run, so it can print only what does not: compartments and refusals. And it cannot show AC4 at all, because expiry takes 72 real hours. A suite that relied on tests like this would be slow, vague, and would never test the deadline.

Each test executable in the example has a CTest label for its level, set in its CMakeLists.txt, so a developer can run the fast tests after every change and the rest before sharing it. (The demo carries only the generic example label that every example on this site gets. -L takes a regular expression, so -L "unit|contract" runs both levels.) These commands were run on this machine, from the GCC build directory; the test numbers depend on the build, and only the matching lines are shown:

$ ctest -R tst_lockers -L unit
1/1 Test #264: tst_lockers_unit_tests ........... Passed 0.00 sec
$ ctest -R tst_lockers -L contract
1/2 Test #265: tst_lockers_memory_store_tests ... Passed 0.00 sec
2/2 Test #266: tst_lockers_file_store_tests ..... Passed 0.00 sec
$ ctest -R tst_lockers -L integration
1/2 Test #266: tst_lockers_file_store_tests ..... Passed 0.00 sec
2/2 Test #268: tst_lockers_integration_tests .... Passed 0.00 sec

The file store’s tests carry both labels, because they are both. In a project this small every level takes milliseconds; the labels start to matter when the integration tests need a database.

A common picture is the test pyramid: many unit tests at the bottom, fewer tests at each level above, and very few end-to-end tests at the top. It is a tendency, not a rule. Its reasoning is the table of levels: lower tests are faster and point at causes, so most checking should happen there.

The right shape follows from where the risk is:

Where the code’s risk is Shape
Rules: pricing, scheduling, allocation, as here Mostly unit and acceptance tests; a contract test per port; a few integration tests
Little logic over a database or a remote service More integration tests: the risk is in the queries and formats, which doubles cannot show
Many implementations of a few interfaces (drivers, plugins) A strong contract test per interface; it is where most of the value is
Wiring of many independent parts A few end-to-end tests that each start the real program

A test that sometimes fails without any change to the code is flaky. Flaky tests can be worse than missing ones: people learn to rerun them and ignore them, and then they ignore a real failure. The usual causes, and how this design avoids them:

  • The real clock. The service reads time only through Clock; the tests use ManualClock.
  • Randomness. Codes come through CodeSource; the tests use a fixed list.
  • Shared files or state. Every test builds its own fixture and its own TempFile, so tests can run in any order, or in parallel.
  • Threads and timing. None here; testing concurrent code has its own page, Testing concurrent code.
  • Undefined behaviour and unspecified order. Reading uninitialised memory, or relying on the iteration order of an std::unordered_map, can give different results on different runs or builds. The sanitizer builds catch the first; MemoryStore uses an ordered std::map, and all() sorts, so the second cannot happen here.

Each of these is a design decision, not a testing one. The ports exist because the tests needed them, and the real program is better for them too: the clock and the code source can be changed without touching the service.

class lockers::ReservationStore

the contract; checked by check_store_contract

Member functions

  • virtual void add(const Reservation& reservation) = 0; may throw AlreadyReserved or invalid_argument; then changes nothing
  • virtual std::optional<Reservation> find(std::string_view code) const = 0;
  • virtual bool remove(std::string_view code) = 0;
  • virtual std::vector<Reservation> all() const = 0; compartment order

class lockers::Clock

Member functions

  • virtual Minutes now() const = 0;

class lockers::CodeSource

Member functions

  • virtual std::string next() = 0;

class lockers::DropOffService

Data members

  • std::vector<Compartment> bank_;
  • ReservationStore& store_;
  • const Clock& clock_;
  • CodeSource& codes_;

Member functions

  • DropOffService(std::vector<Compartment> bank, ReservationStore& store, const Clock& clock, CodeSource& codes);
  • DropOffResult drop_off(Size parcel); AC1, AC2
  • PickUpResult pick_up(std::string_view code); AC3, AC4
  • int release_expired(); AC4
The seams the tests use: three ports into the service, and one contract for the store

When this strategy fits, and when it does not

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

It fits code with real rules and a few dependencies on the outside world, which describes most of the designs on this site. It fits less well when:

  • The program is mostly glue. A tool that copies rows from one database to another has almost no rules; ports and doubles would add code without adding confidence. Test it against real databases.
  • The interface has one implementation, forever. A contract test is still a fine way to write that implementation’s tests, but its main benefit, checking implementations against each other, is gone.
  • The code is a prototype. A program that may be thrown away next week needs a smoke test, not a suite. Write the suite when it is kept, before it grows.
  • Testing everything through the end-to-end path. It is slow, flaky, and its failures point nowhere; and some promises, like a 72-hour deadline, cannot be tested that way at all.
  • Testing nothing but doubles. Every acceptance test passes while the real store loses data. Run the contract test against the real implementation, and keep a few integration tests.
  • A contract test that only one implementation runs. Its value is that every implementation runs it. Add a new implementation to it the day it is written.
  • Testing the same rule at every level. One precise unit test, and an acceptance test of the criterion it serves, is enough. More copies mean more tests to change when the rule changes, without any more confidence.
  • Checking only the reply. “Nothing is reserved” and “nothing is stored” are promises too; check the state after a refusal.
  • Tests that share a file, a database, or a global. They pass alone and fail together, or in a different order.
  • Tests named test1, test2. The name is the first thing anyone reads when it fails.
  • “Add a database store for the head office.” Write it, and add it to the contract test first: check_store_contract with a factory that makes a fresh database store. Add integration tests for what is specific to it, such as two lockers writing at once. The service and its acceptance tests do not change.
  • “Codes expire after 48 hours in stations.” The hold time becomes a setting. The unit test of is_expired does not change; the AC4 acceptance tests gain a case for each setting; the static_assert becomes a test of the default.
  • “A courier may reserve two compartments for one delivery.” A new criterion, so new acceptance tests, written before the code; and the store’s contract may need a new promise, such as adding two reservations together or neither, which every implementation must then pass.

Exercise: Plan tests for a feature

The locker team adds a feature: “A customer may extend a code once, by 24 hours, as long as it has not expired.” The service gains ExtendResult extend(std::string_view code), which returns the new deadline or a refusal (unknown_code, expired, or a new already_extended). Extending must be remembered across a restart.

Plan the tests: list them by level, give each a name, and say which level each belongs to and why. Say which, if any, existing tests change, and what the store’s contract needs. This is a planning exercise; no code is needed.

Show the explained answer

One reasonable plan; others are fine if every promise has a test at the lowest level that can see it.

The criteria, split into promises. Extending adds 24 hours; only once; only before expiry; an unknown code is refused; and the extension survives a restart.

Unit level. If the rule is a pure function, such as extended(const Reservation&, Minutes now), test it directly:

  • extending_adds_24_hours_to_the_deadline
  • a_code_cannot_be_extended_at_or_after_its_deadline, with the deadline minus one minute, the deadline, and one minute after.
  • a_code_cannot_be_extended_twice

Acceptance level, with the manual clock and listed codes:

  • ac5_an_extended_code_works_until_96_hours_after_drop_off: drop off, extend, advance 96 hours minus a minute, pick up; and in a second test, at 96 hours it is expired.
  • ac5_a_code_can_be_extended_only_once: the second extend returns already_extended, and the deadline does not move.
  • ac5_an_expired_code_cannot_be_extended, and that the compartment is still released by release_expired.
  • ac5_an_unknown_code_cannot_be_extended.
  • In each refusal test, check the state as well as the reply: the deadline did not move, and the reservation is otherwise unchanged.

Contract level. The reservation now has an “extended” flag, or the store gains an update operation. Either way it is a new promise every store must keep: “after an update, find returns the updated reservation, and all too”; and if the update can be refused, that a refused update changes nothing. Add those checks to check_store_contract, so both stores run them.

Integration level. One test: extend, restart, and check that the extension is still there and that a second extension is still refused. This catches a file format that forgot the new field. A compatibility test belongs here too: a file written before the change, with no flag, must still load, as unextended reservations. And, as for add, a file-store test that makes the save fail during extend and checks that nothing changed.

Existing tests. None should break: the old criteria still hold. For the existing Reservation{code, compartment, expires} initialisers to keep compiling, the new field needs a default, such as bool extended = false;. The Reservation equality used by the contract test now includes the new field, which is what it should do. If the file format changes, the malformed-file test still applies, and the new test for old files is needed.

  • Tests differ in what they can see, how fast they are, how reliable they are, and how precisely they point at a cause. A strategy mixes them on purpose, and the design decides what is possible.
  • Unit tests check pure rules and their edges. Acceptance tests check each criterion through the service, with test doubles for time, randomness, and storage; name them after the criterion.
  • A contract test writes an interface’s promises down once and runs them against every implementation. It finds the implementation that differs, which tests with doubles never can.
  • Integration tests use the real file, database, or network, for what only the real thing can show. Keep them few, isolated, and self-cleaning; and keep a smoke test of the real program.
  • Keep tests deterministic: time, randomness, and state come through ports the tests control.