# Testing with Fakes: Why This Pays Off

Because the checkout service is handed its clock and its loan repository, a test can hand it a clock set to any day and loans kept in memory, so every late-fee rule and the five-book limit are checked in a few milliseconds, with no database and no waiting; this lesson writes those tests, names the kinds of stand-in (fakes, stubs and mocks), and says what they can't catch.

Journeyman · OOP · Software Development · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Test business rules with a fake clock and an in-memory repository, so each test sets up exactly the day and the data it needs
- Tell a fake, a stub and a mock apart, say what tests with them can't catch, and pick the one a test needs
- Pick this chapter's fix for a problem: hand it in, wire it in one composition root, use a repository, or hand a test a fake

## Key takeaways

- A test double is a stand-in a test hands to the code it tests, in place of the real part.
- A fake is a small working version (loans kept in memory); a stub gives a fixed answer (a clock stuck on one day); a mock records what it was asked, so the test can check.
- With a fake clock and an in-memory repository, each test sets up exactly the day and the loans it needs, and the rules are checked in milliseconds.
- Fakes can't show that the real database code works: a few slower tests against the real thing still do that.

**Before this:** *Dependency Injection* and *Repository: Ask for the Book, Not the Shelf*.

This chapter has changed the checkout service three times, and each change could look like extra work for no new feature. This lesson is the payoff. The library's board has signed off on its rules, and wants every one of them checked, today and after every change anyone makes. Before this chapter, that meant a test database and a calendar. Now it means a few lines each.

## The problem: rules nobody could check

Here are the rules the board signed off on:

| Rule | Example |
|---|---|
| A loan is due 14 days after it's borrowed | borrowed March 2, due March 16 |
| A book returned on time costs nothing | returned March 16: $0.00 |
| Each day late costs $0.25 | 1 day late: $0.25; 6 days late: $1.50 |
| A book never costs more than $5 | 20 days late: $5.00; 40 days late: $5.00 |
| A member can have up to 5 books at once | a sixth is refused |

With version 1, checking "40 days late" meant borrowing a book and waiting 54 days, and checking the limit meant a real database with five real loans in it. So nobody checked, and a mistake in the cap (say, `Math.Max` where `Math.Min` belongs) would have reached members first.

## The fix: hand the test what it needs

A test pilot learns to land in a storm in a flight simulator: the cockpit is real, and everything outside it is a stand-in that can be set to any weather, at any hour, as often as the lesson needs.

![A pilot in a flight simulator's cockpit, the real controls in front of them and a screen outside the window showing a stormy runway at night, while an instructor at a desk behind them turns a dial labeled "weather" to "storm"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/4aa09eeb52e94652b568f7fdac4a2c02.webp)

Tests do the same with the checkout service. The service is real. Its clock and its loans are stand-ins the test sets up: a clock stopped on whatever day the test needs, and loans kept in a plain list in memory. Each test makes its own, so no test can change another's results.

![The same checkout service, used twice: the app hands it the library database's loans and the real clock; a test hands it loans in memory and a clock set to any day. The service box is identical on both sides, labeled "the same code, unchanged"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/11d75095e5d641d7a6ccbc179fb52a33.webp)

The service gets one more question to ask its repository, "how many books does this member have out?", for the five-book limit, and a way to take a returned loan off the list. Each test below borrows on March 2 (due March 16) and moves the clock to the return day:

```csharp
int passed = 0;
CheckFee("On time", 0, 0);
CheckFee("1 day late", 1, 25);
CheckFee("6 days late", 6, 150);
CheckFee("20 days late", 20, 500);
CheckFee("40 days late", 40, 500);
CheckLimit();
Console.WriteLine($"{passed} tests passed, and none of them touched a database or waited a day");

// One test: its own clock and its own loans, set up for exactly this case.
void CheckFee(string test, int daysLate, int expected)
{
    FixedClock clock = new FixedClock(new DateOnly(2026, 3, 2));
    CheckoutService service = new CheckoutService(new InMemoryLoans(), clock);
    Loan loan = service.Borrow("Maya", "The Lighthouse Keeper");
    clock.Today = loan.Due.AddDays(daysLate);
    Report(test, service.ReturnBook(loan.Id) == expected, $"${expected / 100}.{expected % 100:00}");
}

void CheckLimit()
{
    CheckoutService service = new CheckoutService(new InMemoryLoans(), new FixedClock(new DateOnly(2026, 3, 2)));
    for (int book = 1; book <= 5; book++) { service.Borrow("Maya", $"Book {book}"); }
    try
    {
        service.Borrow("Maya", "Rivers of Glass");
        Report("A sixth book is refused", false, "it was lent");
    }
    catch (InvalidOperationException refused)
    {
        Report("A sixth book is refused", true, refused.Message);
    }
}

void Report(string test, bool ok, string detail)
{
    Console.WriteLine($"{test}: {detail}, " + (ok ? "passed" : "failed"));
    if (ok) { passed++; }
}

record Loan(int Id, string Member, string Title, DateOnly Due);
interface IClock { DateOnly Today { get; } }
class FixedClock : IClock { public FixedClock(DateOnly today) => Today = today; public DateOnly Today { get; set; } }

interface ILoanRepository
{
    Loan Add(string member, string title, DateOnly due);
    Loan Find(int id);
    void Remove(int id);
    int CountFor(string member);
}

// A fake: a small, working repository that keeps loans in memory.
class InMemoryLoans : ILoanRepository
{
    private readonly Dictionary<int, Loan> loans = new();
    private int lastId;

    public Loan Add(string member, string title, DateOnly due)
    {
        Loan loan = new Loan(++lastId, member, title, due);
        loans[loan.Id] = loan;
        return loan;
    }

    public Loan Find(int id) => loans[id];
    public void Remove(int id) => loans.Remove(id);
    public int CountFor(string member) => loans.Values.Count(loan => loan.Member == member);
}

class CheckoutService
{
    private readonly ILoanRepository loans;
    private readonly IClock clock;
    public CheckoutService(ILoanRepository loans, IClock clock) { this.loans = loans; this.clock = clock; }

    public Loan Borrow(string member, string title)
    {
        if (loans.CountFor(member) >= 5) { throw new InvalidOperationException($"{member} already has 5 books"); }
        return loans.Add(member, title, clock.Today.AddDays(14));
    }

    public int ReturnBook(int id)
    {
        Loan loan = loans.Find(id);
        loans.Remove(id);
        return Math.Min(Math.Max(0, clock.Today.DayNumber - loan.Due.DayNumber) * 25, 500);
    }
}
```

```text
On time: $0.00, passed
1 day late: $0.25, passed
6 days late: $1.50, passed
20 days late: $5.00, passed
40 days late: $5.00, passed
A sixth book is refused: Maya already has 5 books, passed
6 tests passed, and none of them touched a database or waited a day
```

```java
record Loan(int id, String member, String title, LocalDate due) { }
interface Clock { LocalDate today(); }
class FixedClock implements Clock { LocalDate day; FixedClock(LocalDate day) { this.day = day; } public LocalDate today() { return day; } }

interface LoanRepository {
    Loan add(String member, String title, LocalDate due);
    Loan find(int id);
    void remove(int id);
    int countFor(String member);
}

// A fake: a small, working repository that keeps loans in memory.
class InMemoryLoans implements LoanRepository {
    private final Map<Integer, Loan> loans = new HashMap<>();
    private int lastId;

    public Loan add(String member, String title, LocalDate due) {
        Loan loan = new Loan(++lastId, member, title, due);
        loans.put(loan.id(), loan);
        return loan;
    }

    public Loan find(int id) { return loans.get(id); }
    public void remove(int id) { loans.remove(id); }
    public int countFor(String member) { return (int) loans.values().stream().filter(loan -> loan.member().equals(member)).count(); }
}

class CheckoutService {
    private final LoanRepository loans;
    private final Clock clock;
    CheckoutService(LoanRepository loans, Clock clock) { this.loans = loans; this.clock = clock; }

    Loan borrow(String member, String title) {
        if (loans.countFor(member) >= 5) { throw new IllegalStateException(member + " already has 5 books"); }
        return loans.add(member, title, clock.today().plusDays(14));
    }

    int returnBook(int id) {
        Loan loan = loans.find(id);
        loans.remove(id);
        return (int) Math.min(Math.max(0, ChronoUnit.DAYS.between(loan.due(), clock.today())) * 25, 500);
    }
}

int passed = 0;

void report(String test, boolean ok, String detail) {
    IO.println(test + ": " + detail + ", " + (ok ? "passed" : "failed"));
    if (ok) { passed++; }
}

// One test: its own clock and its own loans, set up for exactly this case.
void checkFee(String test, int daysLate, int expected) {
    FixedClock clock = new FixedClock(LocalDate.of(2026, 3, 2));
    CheckoutService service = new CheckoutService(new InMemoryLoans(), clock);
    Loan loan = service.borrow("Maya", "The Lighthouse Keeper");
    clock.day = loan.due().plusDays(daysLate);
    report(test, service.returnBook(loan.id()) == expected, String.format("$%d.%02d", expected / 100, expected % 100));
}

void checkLimit() {
    CheckoutService service = new CheckoutService(new InMemoryLoans(), new FixedClock(LocalDate.of(2026, 3, 2)));
    for (int book = 1; book <= 5; book++) { service.borrow("Maya", "Book " + book); }
    try {
        service.borrow("Maya", "Rivers of Glass");
        report("A sixth book is refused", false, "it was lent");
    } catch (IllegalStateException refused) {
        report("A sixth book is refused", true, refused.getMessage());
    }
}

void main() {
    checkFee("On time", 0, 0);
    checkFee("1 day late", 1, 25);
    checkFee("6 days late", 6, 150);
    checkFee("20 days late", 20, 500);
    checkFee("40 days late", 40, 500);
    checkLimit();
    IO.println(passed + " tests passed, and none of them touched a database or waited a day");
}
```

```text
On time: $0.00, passed
1 day late: $0.25, passed
6 days late: $1.50, passed
20 days late: $5.00, passed
40 days late: $5.00, passed
A sixth book is refused: Maya already has 5 books, passed
6 tests passed, and none of them touched a database or waited a day
```

```python
from dataclasses import dataclass
from datetime import date, timedelta


@dataclass
class Loan:
    id: int
    member: str
    title: str
    due: date


class FixedClock:
    def __init__(self, day):
        self.day = day

    def today(self):
        return self.day


class InMemoryLoans:
    """A fake: a small, working repository that keeps loans in memory."""

    def __init__(self):
        self.loans = {}
        self.last_id = 0

    def add(self, member, title, due):
        self.last_id += 1
        loan = Loan(self.last_id, member, title, due)
        self.loans[loan.id] = loan
        return loan

    def find(self, id):
        return self.loans[id]

    def remove(self, id):
        del self.loans[id]

    def count_for(self, member):
        return sum(1 for loan in self.loans.values() if loan.member == member)


class CheckoutService:
    def __init__(self, loans, clock):
        self.loans = loans
        self.clock = clock

    def borrow(self, member, title):
        if self.loans.count_for(member) >= 5:
            raise ValueError(f"{member} already has 5 books")
        return self.loans.add(member, title, self.clock.today() + timedelta(days=14))

    def return_book(self, id):
        loan = self.loans.find(id)
        self.loans.remove(id)
        return min(max(0, (self.clock.today() - loan.due).days) * 25, 500)


passed = 0


def report(test, ok, detail):
    global passed
    print(f"{test}: {detail}, " + ("passed" if ok else "failed"))
    if ok:
        passed += 1


def check_fee(test, days_late, expected):
    """One test: its own clock and its own loans, set up for exactly this case."""
    clock = FixedClock(date(2026, 3, 2))
    service = CheckoutService(InMemoryLoans(), clock)
    loan = service.borrow("Maya", "The Lighthouse Keeper")
    clock.day = loan.due + timedelta(days=days_late)
    report(test, service.return_book(loan.id) == expected, f"${expected // 100}.{expected % 100:02d}")


def check_limit():
    service = CheckoutService(InMemoryLoans(), FixedClock(date(2026, 3, 2)))
    for book in range(1, 6):
        service.borrow("Maya", f"Book {book}")
    try:
        service.borrow("Maya", "Rivers of Glass")
        report("A sixth book is refused", False, "it was lent")
    except ValueError as refused:
        report("A sixth book is refused", True, str(refused))


check_fee("On time", 0, 0)
check_fee("1 day late", 1, 25)
check_fee("6 days late", 6, 150)
check_fee("20 days late", 20, 500)
check_fee("40 days late", 40, 500)
check_limit()
print(f"{passed} tests passed, and none of them touched a database or waited a day")
```

```text
On time: $0.00, passed
1 day late: $0.25, passed
6 days late: $1.50, passed
20 days late: $5.00, passed
40 days late: $5.00, passed
A sixth book is refused: Maya already has 5 books, passed
6 tests passed, and none of them touched a database or waited a day
```

```javascript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day, days) => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

class FixedClock { constructor(day) { this.day = day; } today() { return this.day; } }

// A fake: a small, working repository that keeps loans in memory.
class InMemoryLoans {
  #loans = new Map();
  #lastId = 0;
  add(member, title, due) {
    const loan = { id: ++this.#lastId, member, title, due };
    this.#loans.set(loan.id, loan);
    return loan;
  }
  find(id) { return this.#loans.get(id); }
  remove(id) { this.#loans.delete(id); }
  countFor(member) { return [...this.#loans.values()].filter((loan) => loan.member === member).length; }
}

class CheckoutService {
  #loans;
  #clock;
  constructor(loans, clock) { this.#loans = loans; this.#clock = clock; }
  borrow(member, title) {
    if (this.#loans.countFor(member) >= 5) { throw new Error(`${member} already has 5 books`); }
    return this.#loans.add(member, title, addDays(this.#clock.today(), 14));
  }
  returnBook(id) {
    const loan = this.#loans.find(id);
    this.#loans.remove(id);
    return Math.min(Math.max(0, daysBetween(loan.due, this.#clock.today())) * 25, 500);
  }
}

let passed = 0;

function report(test, ok, detail) {
  console.log(`${test}: ${detail}, ` + (ok ? "passed" : "failed"));
  if (ok) { passed++; }
}

// One test: its own clock and its own loans, set up for exactly this case.
function checkFee(test, daysLate, expected) {
  const clock = new FixedClock("2026-03-02");
  const service = new CheckoutService(new InMemoryLoans(), clock);
  const loan = service.borrow("Maya", "The Lighthouse Keeper");
  clock.day = addDays(loan.due, daysLate);
  report(test, service.returnBook(loan.id) === expected, `$${(expected / 100).toFixed(2)}`);
}

function checkLimit() {
  const service = new CheckoutService(new InMemoryLoans(), new FixedClock("2026-03-02"));
  for (let book = 1; book <= 5; book++) { service.borrow("Maya", `Book ${book}`); }
  try {
    service.borrow("Maya", "Rivers of Glass");
    report("A sixth book is refused", false, "it was lent");
  } catch (refused) {
    report("A sixth book is refused", true, refused.message);
  }
}

checkFee("On time", 0, 0);
checkFee("1 day late", 1, 25);
checkFee("6 days late", 6, 150);
checkFee("20 days late", 20, 500);
checkFee("40 days late", 40, 500);
checkLimit();
console.log(`${passed} tests passed, and none of them touched a database or waited a day`);
```

```text
On time: $0.00, passed
1 day late: $0.25, passed
6 days late: $1.50, passed
20 days late: $5.00, passed
40 days late: $5.00, passed
A sixth book is refused: Maya already has 5 books, passed
6 tests passed, and none of them touched a database or waited a day
```

```typescript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day: string, days: number): string => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from: string, to: string): number => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

interface Loan { id: number; member: string; title: string; due: string; }
interface Clock { today(): string; }
class FixedClock implements Clock { day: string; constructor(day: string) { this.day = day; } today(): string { return this.day; } }

interface LoanRepository {
  add(member: string, title: string, due: string): Loan;
  find(id: number): Loan;
  remove(id: number): void;
  countFor(member: string): number;
}

// A fake: a small, working repository that keeps loans in memory.
class InMemoryLoans implements LoanRepository {
  private loans = new Map<number, Loan>();
  private lastId = 0;
  add(member: string, title: string, due: string): Loan {
    const loan = { id: ++this.lastId, member, title, due };
    this.loans.set(loan.id, loan);
    return loan;
  }
  find(id: number): Loan { return this.loans.get(id)!; }
  remove(id: number): void { this.loans.delete(id); }
  countFor(member: string): number { return [...this.loans.values()].filter((loan) => loan.member === member).length; }
}

class CheckoutService {
  private readonly loans: LoanRepository;
  private readonly clock: Clock;
  constructor(loans: LoanRepository, clock: Clock) { this.loans = loans; this.clock = clock; }
  borrow(member: string, title: string): Loan {
    if (this.loans.countFor(member) >= 5) { throw new Error(`${member} already has 5 books`); }
    return this.loans.add(member, title, addDays(this.clock.today(), 14));
  }
  returnBook(id: number): number {
    const loan = this.loans.find(id);
    this.loans.remove(id);
    return Math.min(Math.max(0, daysBetween(loan.due, this.clock.today())) * 25, 500);
  }
}

let passed = 0;

function report(test: string, ok: boolean, detail: string): void {
  console.log(`${test}: ${detail}, ` + (ok ? "passed" : "failed"));
  if (ok) { passed++; }
}

// One test: its own clock and its own loans, set up for exactly this case.
function checkFee(test: string, daysLate: number, expected: number): void {
  const clock = new FixedClock("2026-03-02");
  const service = new CheckoutService(new InMemoryLoans(), clock);
  const loan = service.borrow("Maya", "The Lighthouse Keeper");
  clock.day = addDays(loan.due, daysLate);
  report(test, service.returnBook(loan.id) === expected, `$${(expected / 100).toFixed(2)}`);
}

function checkLimit(): void {
  const service = new CheckoutService(new InMemoryLoans(), new FixedClock("2026-03-02"));
  for (let book = 1; book <= 5; book++) { service.borrow("Maya", `Book ${book}`); }
  try {
    service.borrow("Maya", "Rivers of Glass");
    report("A sixth book is refused", false, "it was lent");
  } catch (refused) {
    report("A sixth book is refused", true, (refused as Error).message);
  }
}

checkFee("On time", 0, 0);
checkFee("1 day late", 1, 25);
checkFee("6 days late", 6, 150);
checkFee("20 days late", 20, 500);
checkFee("40 days late", 40, 500);
checkLimit();
console.log(`${passed} tests passed, and none of them touched a database or waited a day`);
```

```text
On time: $0.00, passed
1 day late: $0.25, passed
6 days late: $1.50, passed
20 days late: $5.00, passed
40 days late: $5.00, passed
A sixth book is refused: Maya already has 5 books, passed
6 tests passed, and none of them touched a database or waited a day
```

Six tests of five rules, checked in a few milliseconds, on any computer, in any order. Each test makes its own clock and its own loans, so none can change another's results: the tests are **isolated**. Put the bug from earlier in (`Math.Max(..., 500)` for the cap) and "20 days late" and "40 days late" fail at once, before any member is overcharged.

**Where the languages differ.** Each language refuses the sixth book with its own kind of exception: `InvalidOperationException` in C#, `IllegalStateException` in Java, `ValueError` in Python and a plain `Error` in JavaScript and TypeScript. At work these checks live in each language's test tool (MSTest, JUnit, pytest, `node --test`), as this chapter's exercise shows; here they're plain code, so you can see there's nothing more to it.

## Fakes, stubs and mocks

A stand-in that a test hands to the code it tests, in place of the real part, is a **test double** (as in a stunt double for a film's star). There are a few kinds, and teams use the names loosely, so it's worth knowing what each one means:

| Kind | What it is | In this chapter |
|---|---|---|
| **Fake** | a small, working version of the real thing, too simple for the real app | `InMemoryLoans`: it really adds, finds and counts loans, in a list |
| **Stub** | gives a fixed answer it was set up with, and does nothing else | a clock stopped on March 2: "what day is it?" always gets the day the test chose |
| **Mock** | records what it was asked, so the test can check that a call happened | a pretend email sender that keeps a list of the reminders it was asked to send, so the test can check one went to Maya |

Pick the simplest one that lets the test say what it means. A stub when the code only needs an answer; a fake when the code saves and reads things back; a mock only when the call itself is the point ("a reminder was sent"). Test tools such as Moq, Mockito, `unittest.mock` and Jest can make mocks for you, but every one of them is the idea in this table.

## What fakes can't tell you

A fake proves the *rules* are right. It can't prove the *real parts* are:

- **`DatabaseLoans` itself** still needs tests against a real database: is the column called `due`, does the date come back as the same date? Those tests are slower, so a project has a few of them, not hundreds. They're often called **integration tests**: they check that two real parts work together.
- **A fake that breaks the promise** makes tests pass that shouldn't. If `InMemoryLoans.Remove` did nothing, the five-book test would still pass today, and a later test could fail for no clear reason. A good habit: run the same few tests against both keepers of the promise, the fake and the real one, so they're known to behave alike.
- **A test that reads the real clock** passes or fails depending on the day it runs. That's a **flaky test**, and it's exactly what a fake clock prevents.

## How this chapter's fixes fit together

| The problem | The fix | Lesson |
|---|---|---|
| A class builds or reaches for what it uses, so nobody can change it | Hand it in through the constructor | *Dependency Injection* |
| The building is copied all over the app | One composition root, or a container | *Containers* |
| Business code speaks the database's language | A repository, in the app's own words | *Repository* |
| The rules can't be checked without waiting or a database | Hand the tests a fake clock and loans in memory | this lesson |

## Check yourself

2 questions to try on the lesson page.

## So what

Handing a class what it needs looked like extra ceremony two lessons ago. This is what it buys: every rule the board cares about, checked in milliseconds, by tests that can't interfere with each other. The exercise next asks you to make that change yourself, under tests, on a checkout service that still builds its own storage.

## Key terms

- [Test Double](https://www.ask-codey.com/glossary/test-double)
- [Stub and Fake](https://www.ask-codey.com/glossary/stub-and-fake)
- [Test Isolation](https://www.ask-codey.com/glossary/test-isolation)
- [Flaky Test](https://www.ask-codey.com/glossary/flaky-test)

## Cheat sheets

- [Testing with Fakes: Why This Pays Off](https://www.ask-codey.com/cheat-sheets/dp-testing-with-fakes-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-testing-with-fakes
