← C++

C++ · 18 / 24

Replaceable repositories and focused test doubles

Develop an application service independently of its storage and test read and write failures separately.

  • Large
  • Advanced
  • 90 min

Prerequisites: Headers, CMake and first unit tests, Ownership, lifetime and move semantics, Error handling and the strong exception guarantee

In this tutorial
  1. Define a small contract
  2. Keep rules in the application core
  3. Wire dependencies at startup
  4. Inject read failures
  5. Test write failures independently
  6. Explain the architecture
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20, CMake 3.25 or later, CTest and Python 3. Extract the ZIP into a new folder. python3 run_checks.py checks example and solution in a temporary copy and preserves your files. Run python3 verify.py for your own build. The demo is then available at build/order_lab. No additional libraries are required. The documented commands were checked on Linux.

Verified on 2026-10-21 on Linux x86_64. In-memory implementation, updates and deletion, read-error propagation without a subsequent write, and separate write failures. Multi-process conflicts are outside this example.

A UI should save orders without knowing SQL. OrderService describes that operation. OrderRepository defines what persistence must provide. An in-memory implementation makes tests fast. Failure implementations show that the service propagates errors and never writes after a failed read.

Package contents and individual files

01Define a small contract

The repository provides list and replaceAll. replaceAll is atomic from the caller's perspective: failure preserves the last committed batch. A virtual destructor enables correct polymorphic destruction. OrderService borrows a reference, so the repository must outlive the service.

repository.hpp · cppOpen file
#pragma once
#include "order.hpp"

namespace orders {
class OrderRepository {
public:
  virtual ~OrderRepository() = default;
  virtual Result<std::vector<Order>> list() const = 0;
  // Contract: failure leaves the previously committed batch intact.
  virtual Result<Done> replaceAll(std::span<const Order> batch) = 0;
};
class MemoryRepository final : public OrderRepository {
  std::vector<Order> data_;

public:
  Result<std::vector<Order>> list() const override { return data_; }
  Result<Done> replaceAll(std::span<const Order> batch) override {
    return replaceValidated(data_, batch);
  }
};
class OrderService {
  OrderRepository &repository_;

public:
  explicit OrderService(OrderRepository &repository)
      : repository_(repository) {}
  Result<std::vector<Order>> list() const { return repository_.list(); }
  Result<Done> replace(std::span<const Order> batch) {
    auto result = validateBatch(batch);
    if (!succeeded(result))
      return std::get<Error>(result);
    return repository_.replaceAll(batch);
  }
  Result<Done> save(const Order &order) {
    auto result = repository_.list();
    if (!succeeded(result))
      return std::get<Error>(result);
    auto batch = std::get<std::vector<Order>>(std::move(result));
    auto found = std::ranges::find(batch, order.id, &Order::id);
    if (found == batch.end())
      batch.push_back(order);
    else
      *found = order;
    return replace(batch);
  }
  Result<Done> remove(int id) {
    auto result = repository_.list();
    if (!succeeded(result))
      return std::get<Error>(result);
    auto batch = std::get<std::vector<Order>>(std::move(result));
    std::erase_if(batch, [id](const Order &order) { return order.id == id; });
    return replace(batch);
  }
};
} // namespace orders
Expected result

The service knows neither filenames nor SQL connections.

02Keep rules in the application core

Validation remains independent of Qt and database drivers. The service validates a batch before handing it over. Concrete repositories also enforce their contract so direct calls cannot introduce invalid data. This component boundary does not replace database constraints.

order.hpp · cppOpen file
#pragma once
#include "result.hpp"
#include <algorithm>
#include <ranges>
#include <set>
#include <span>
#include <string_view>
#include <vector>

namespace orders {
enum class Status { open, done };
struct Order {
  int id;
  std::string title;
  int priority{0};
  Status status{Status::open};
  bool operator==(const Order &) const = default;
};
inline Result<Done> validate(const Order &order) {
  const bool blank = std::ranges::all_of(order.title, [](char c) {
    return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  });
  if (order.id < 1 || order.id > 1000000 || order.title.empty() ||
      order.title.size() > 80 || blank || order.priority < 0 ||
      order.priority > 2 ||
      (order.status != Status::open && order.status != Status::done))
    return Error{ErrorCode::invalid, "ID 1..1000000, title 1..80 UTF-8 bytes, "
                                     "priority 0..2 and valid status required"};
  return Done{};
}
inline Result<Done> validateBatch(std::span<const Order> batch) {
  if (batch.size() > 1000)
    return Error{ErrorCode::invalid, "At most 1000 orders are allowed"};
  std::set<int> ids;
  for (const auto &order : batch) {
    auto result = validate(order);
    if (!succeeded(result))
      return std::get<Error>(result);
    if (!ids.insert(order.id).second)
      return Error{ErrorCode::duplicate, "Duplicate order ID"};
  }
  return Done{};
}
inline std::vector<int> matchingIds(std::span<const Order> values,
                                    std::string_view needle) {
  // Both views borrow their input. Consume them before the owner changes.
  auto matching =
      values | std::views::filter([needle](const Order &order) {
        return order.status == Status::open &&
               order.title.find(needle) != std::string::npos;
      }) |
      std::views::transform([](const Order &order) { return order.id; });
  return {matching.begin(), matching.end()};
}
inline Result<Done> replaceValidated(std::vector<Order> &current,
                                     std::span<const Order> incoming) {
  auto result = validateBatch(incoming);
  if (!succeeded(result))
    return std::get<Error>(result);
  std::vector<Order> candidate(incoming.begin(), incoming.end());
  // Validation and allocations precede this non-throwing commit point.
  current.swap(candidate);
  return Done{};
}
} // namespace orders
Expected result

Blank titles and duplicate IDs never result in successful storage.

03Wire dependencies at startup

main constructs the repository before the service. save adds a new ID or updates an existing order. The example deliberately has one writing application flow. Concurrent read-modify-write from several processes would need an additional conflict contract.

main.cpp · cppOpen file
#include "repository.hpp"
#include "test_support.hpp"
int main() {
  orders::MemoryRepository repository;
  orders::OrderService service(repository);
  service.save({1, "Deliver motors", 2});
  std::cout << "Saved orders: "
            << std::get<std::vector<orders::Order>>(service.list()).size()
            << '\n';
}
Expected result

Saved orders: 1

04Inject read failures

Unavailable returns a storage error on reads. Its write method deliberately throws a logic error. The test invokes save and expects the read error. If the service wrote anyway, the test program would fail. The real in-memory implementation also exercises updating and deletion.

tests.cpp · cppOpen file
#include "repository.hpp"
#include "test_support.hpp"
class Unavailable final : public orders::OrderRepository {
public:
  orders::Result<std::vector<orders::Order>> list() const override {
    return orders::Error{orders::ErrorCode::storage, "Disk unavailable"};
  }
  orders::Result<orders::Done>
  replaceAll(std::span<const orders::Order>) override {
    throw std::logic_error("save must not write after failed read");
  }
};
int main() {
  orders::MemoryRepository memory;
  orders::OrderService service(memory);
  require(orders::succeeded(service.replace(samples())), "seed");
  require(orders::succeeded(service.save({2, "Updated", 1})), "update");
  require(std::get<std::vector<orders::Order>>(service.list())[1].title ==
              "Updated",
          "persisted update");
  require(orders::succeeded(service.remove(1)), "remove");
  require(std::get<std::vector<orders::Order>>(service.list()).size() == 2,
          "removed one");
  Unavailable unavailable;
  orders::OrderService offline(unavailable);
  auto failed = offline.save({9, "Order", 0});
  require(!orders::succeeded(failed), "read failure propagated without write");
  std::cout << "repository contract checks passed\n";
}
Expected result

A failed read causes no write attempt.

05Test write failures independently

The second test double allows reads and rejects writes, so the service actually reaches its persistence boundary. Test both save and remove and compare the entire batch afterward. A double that only fails on reads cannot cover this error handling.

solution.cpp · cppOpen file
#include "repository.hpp"
#include "test_support.hpp"
class WriteFailure final : public orders::OrderRepository {
  orders::MemoryRepository data_;

public:
  WriteFailure() { data_.replaceAll(samples()); }
  orders::Result<std::vector<orders::Order>> list() const override {
    return data_.list();
  }
  orders::Result<orders::Done>
  replaceAll(std::span<const orders::Order>) override {
    return orders::Error{orders::ErrorCode::storage, "Simulated write failure"};
  }
};
int main() {
  WriteFailure repository;
  orders::OrderService service(repository);
  require(!orders::succeeded(service.save({9, "Cannot save"})),
          "write error returned");
  require(!orders::succeeded(service.remove(1)), "delete error returned");
  require(std::get<std::vector<orders::Order>>(service.list()) == samples(),
          "data unchanged");
}
Expected result

Both operations report failure and preserve the original data.

06Explain the architecture

Run python3 verify.py. All tests run without Qt, a network or a database, demonstrating the core's dependency direction. Tutorial 21 implements the same interface using SQLite. A test double alone does not establish that the later implementation uses transactions correctly.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(cpp_18 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
enable_testing()
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
  add_compile_options(-Wall -Wextra -Wpedantic -Werror)
endif()
add_executable(order_lab main.cpp)
add_executable(lesson_tests tests.cpp)
add_test(NAME lesson_tests COMMAND lesson_tests)
set_tests_properties(lesson_tests PROPERTIES TIMEOUT 30)
add_executable(exercise_solution solution.cpp)
add_test(NAME exercise_solution COMMAND exercise_solution)
set_tests_properties(exercise_solution PROPERTIES TIMEOUT 30)
Expected result

Two test programs pass without external services.

Your exercise

Build a repository that permits reading sample data but rejects every write with ErrorCode::storage. Test save, remove and the entire resulting state.

Show the solution and explanation

WriteFailure wraps MemoryRepository for reads and returns an error on writes. Tests demonstrate that the service never reports a successful change and stored orders are preserved.

solution.cpp · cppOpen file
#include "repository.hpp"
#include "test_support.hpp"
class WriteFailure final : public orders::OrderRepository {
  orders::MemoryRepository data_;

public:
  WriteFailure() { data_.replaceAll(samples()); }
  orders::Result<std::vector<orders::Order>> list() const override {
    return data_.list();
  }
  orders::Result<orders::Done>
  replaceAll(std::span<const orders::Order>) override {
    return orders::Error{orders::ErrorCode::storage, "Simulated write failure"};
  }
};
int main() {
  WriteFailure repository;
  orders::OrderService service(repository);
  require(!orders::succeeded(service.save({9, "Cannot save"})),
          "write error returned");
  require(!orders::succeeded(service.remove(1)), "delete error returned");
  require(std::get<std::vector<orders::Order>>(service.list()) == samples(),
          "data unchanged");
}

Project context and sources

Independent teaching project using FactoryForge's logistics theme. The existing FactoryForge source revision provides architectural context. SQLite, networking and import features introduced here belong to the teaching project. Order Lab JSON is a separate format.