Lesson 30 of 93 · 6 min read · Updated

Fake and Spy Test Doubles in C#: Working State and Recorded Calls

A stub hands back fixed answers and forgets everything else. Some scenarios need more: the stock must really go down after an order, or the test must see which emails were sent. This lesson adds two doubles that do real work. A fake is a simplified but working implementation, and a spy records the calls it receives so the test can inspect them afterwards. Both are written by hand for the same OrderService.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. No mocking library: the fake and the spy are plain C# classes.

Fake: A Working, Simplified Implementation

FakeInventory keeps stock in a dictionary. Reserve subtracts from it, and asking for more than is available throws, just as a real store would refuse. It does not talk to a database, so tests stay fast, but it behaves like a real inventory.

M04.TestDoubles.Tests/Doubles/FakeInventory.cs

using M04.TestDoubles.Ports;

namespace M04.TestDoubles.Tests.Doubles;

/// <summary>
/// FAKE: "a working but simplified implementation".
///
/// The difference from a stub: it has REAL BEHAVIOUR. When you reserve,
/// the stock really goes down. That lets us test STATE-based scenarios such as
/// "if two orders are placed, the second one is rejected".
///
/// Typical example: an in-memory repository. Tests stay fast, but
/// the scenario behaves like a real store.
/// </summary>
public sealed class FakeInventory : IInventory
{
private readonly Dictionary<string, int> _stock;

public FakeInventory(IDictionary<string, int>? initialStock = null)
{
_stock = initialStock is null ? [] : new Dictionary<string, int>(initialStock);
}

public int AvailableQuantity(string sku) => _stock.GetValueOrDefault(sku, 0);

public void Reserve(string sku, int quantity)
{
var available = AvailableQuantity(sku);
if (quantity > available)
{
// We behave like a real store: we do not silently accept an invalid state.
throw new InvalidOperationException($"'{sku}' için yeterli stok yok."); // "Not enough stock for ..."
}

_stock[sku] = available - quantity;
}
}

Two details matter. The constructor copies the initial dictionary, so the test's own dictionary is never changed behind its back. And Reserve refuses invalid requests instead of letting stock go negative. A fake that accepts impossible states would hide bugs in the code under test.

A fake is code, so it can be wrong. Keep it small and give it the same rules as the real implementation. If the real store and the fake drift apart, your tests pass against behaviour that production does not have. For larger fakes, some teams run the same contract tests against both the fake and the real implementation.

The Test a Stub Cannot Write

Place the same order twice when only one item is in stock. The first order should succeed and the second should fail.

M04.TestDoubles.Tests/FakeAndSpyTests.cs

[Fact]
public void Place_Twice_SecondOrderFails_BecauseFakeActuallyDecrementsStock()
{
// What a FAKE gives us: STATE.
// We could not set up this scenario with a stub, because a stub swallows the reservation.
var inventory = new FakeInventory(new Dictionary<string, int> { ["MOUSE-01"] = 1 });
var sut = new OrderService(
inventory,
new StubOrderNumberGenerator("SIP-1"),
new SpyEmailSender(),
new DummyAuditLog());

var first = sut.Place("ali@ornek.com", [new OrderLine("MOUSE-01", 1, 250m)]);
var second = sut.Place("ali@ornek.com", [new OrderLine("MOUSE-01", 1, 250m)]);

Assert.True(first.IsSuccessful);
Assert.False(second.IsSuccessful);
Assert.Equal(0, inventory.AvailableQuantity("MOUSE-01"));
}

Try this with StubInventory. Its Reserve does nothing, so AvailableQuantity keeps returning 1 and the second order succeeds too. The test would fail, not because the service is wrong, but because the double cannot represent the scenario.

This is the limit of the rule "use the lightest double". A stub is lighter than a fake, but when the scenario depends on state changing between calls, a stub is not enough. Pick the lightest double that can still express the scenario.

The last assertion reads the state of the fake directly: zero items left. That is a state check, and it survives refactoring well. It does not care how the service reserved the stock, only that the stock is gone.

Spy: Record Now, Check Later

IEmailSender returns nothing, so the test cannot see its effect through a return value. A spy solves this by keeping a list of every call it receives.

M04.TestDoubles.Tests/Doubles/SpyEmailSender.cs

using M04.TestDoubles.Ports;

namespace M04.TestDoubles.Tests.Doubles;

/// <summary>
/// SPY: "records what happened".
///
/// A spy RECORDS the calls; the test's Assert section does the verification.
/// The difference from a mock: it does not set up the expectation BEFOREHAND, it inspects AFTERWARDS.
/// This keeps the test's Arrange–Act–Assert flow intact and easy to read.
/// </summary>
public sealed class SpyEmailSender : IEmailSender
{
private readonly List<(string ToAddress, string OrderNumber)> _sent = [];

/// <summary>The record of sent emails.</summary>
public IReadOnlyList<(string ToAddress, string OrderNumber)> Sent => _sent;

public void SendOrderConfirmation(string toAddress, string orderNumber) =>
_sent.Add((toAddress, orderNumber));
}

The spy exposes its record as IReadOnlyList, so a test can read it but cannot change it by accident. Each entry is a named tuple, which makes assertions read like plain sentences.

M04.TestDoubles.Tests/FakeAndSpyTests.cs

[Fact]
public void Place_WhenSuccessful_SpyRecordsSingleConfirmationEmail()
{
var spy = new SpyEmailSender();
var sut = new OrderService(
new FakeInventory(new Dictionary<string, int> { ["KLAVYE-01"] = 5 }),
new StubOrderNumberGenerator("SIP-2026-0007"),
spy,
new DummyAuditLog());

sut.Place("ayse@ornek.com", [new OrderLine("KLAVYE-01", 2, 750m)]);

// The SPY is checked in the Assert section, in a readable way.
var sent = Assert.Single(spy.Sent);
Assert.Equal("ayse@ornek.com", sent.ToAddress);
Assert.Equal("SIP-2026-0007", sent.OrderNumber);
}

Assert.Single does two jobs: it fails if the list does not have exactly one item, and it returns that item for the next assertions. The test checks the recipient and the order number, which are the facts the customer cares about.

Because the spy only records, the test keeps a clean Arrange, Act, Assert shape. Nothing about the expected email appears before the Act line. You read the setup, then the action, then what should have happened.

Checking That Something Did Not Happen

A spy also proves that a call did not happen. When stock is missing, the customer must not get a confirmation email.

M04.TestDoubles.Tests/FakeAndSpyTests.cs

[Fact]
public void Place_WhenStockIsInsufficient_NoEmailIsSent()
{
var spy = new SpyEmailSender();
var sut = new OrderService(
new FakeInventory(new Dictionary<string, int> { ["KLAVYE-01"] = 0 }),
new StubOrderNumberGenerator("SIP-X"),
spy,
new DummyAuditLog());

sut.Place("ayse@ornek.com", [new OrderLine("KLAVYE-01", 1, 750m)]);

// Behaviour that "must not happen" is part of the contract too.
Assert.Empty(spy.Sent);
}

Negative checks like this catch a real class of bugs: a refactoring that moves the email call above the stock check would send a confirmation for an order that never existed.

Common mistake: spying on everything. Use a spy for outgoing effects that matter to the business, such as emails or published messages. Recording every call to the inventory and asserting on that list would tie the test to internal steps, which is exactly what the stub rule from the previous lesson warns against.

Summary

  1. A fake is a simplified implementation with real behaviour, such as an in-memory store that really decrements stock.
  2. Use a fake when the scenario depends on state changing between calls. A stub swallows commands and cannot express that.
  3. A spy records the calls it receives. The test checks the record in its Assert section, so the Arrange, Act, Assert flow stays readable.
  4. A spy can also prove that an outgoing call did not happen, which is part of the contract too.
  5. Spy only on outgoing effects that matter to the business. The next lesson shows the mock, which knows its expectation in advance.