Fakes and Mocks: The Stand-Ins

Fakes and Mocks: The Stand-Ins in C#: A film set is full of things that are not what they appear to be.

The Analogy: The Film Set

A film set is full of things that are not what they appear to be. The star's stand-in occupies their mark while the lighting crew works, because the star's time is expensive. The stunt double takes the fall. The telephone on the desk is a prop that dials nobody, and the whisky in the glass is cold tea. None of this is deception — it is the only way to shoot the scene at all.

A unit test is the same shoot. The code you want to film is the service; the payment gateway, the email server and the system clock are the expensive, dangerous and uncooperative co-stars. You replace them with stand-ins so that the scene runs in milliseconds, produces the same result every time, and charges nobody's card.

The stand-ins come in kinds, and the words matter because they describe different questions. A stub delivers scripted lines: ask it anything and it returns the canned answer. A spy does the same but writes down what it was asked, so afterwards you can check whether the phone was actually dialled. A fake is a working prop — a kettle that really boils, a repository that really stores, just in memory rather than in a data centre. A mock is a stand-in holding a rehearsal script who objects when you deviate from it.

The temptation on a film set is to build a stand-in for everything, until the whole scene is props and none of it is the film. Tests get the same disease: a service surrounded by six mocks, each asserting the exact order of calls, is a test of the current implementation rather than of the behaviour. Replace what is slow, non-deterministic or outward-facing. Use the real thing for everything else.


Syntax or Core Structure

Test doubles are ordinary classes implementing the interfaces your service depends on. No library is required for the shape:

interface IEmailSender
{
    Task SendAsync(string to, string subject);
}

interface IClock
{
    DateTimeOffset UtcNow { get; }
}

sealed class WelcomeService
{
    private readonly IEmailSender _email;
    private readonly IClock _clock;

    public WelcomeService(IEmailSender email, IClock clock)
    {
        _email = email;
        _clock = clock;
    }

    public async Task<string> WelcomeAsync(string name)
    {
        string greeting = _clock.UtcNow.Hour < 12 ? "Good morning" : "Good afternoon";
        await _email.SendAsync(name + "@example.test", greeting + ", " + name);
        return greeting;
    }
}

Two stand-ins cover it — a clock that always says the same thing, and a mail sender that keeps the post instead of sending it:

// A stub: a canned answer, nothing recorded.
sealed class FixedClock : IClock
{
    public FixedClock(DateTimeOffset now) => UtcNow = now;

    public DateTimeOffset UtcNow { get; }
}

// A spy: the same, plus a record of what it was asked to do.
sealed class EmailSpy : IEmailSender
{
    public List<(string To, string Subject)> Sent { get; } = new();

    public Task SendAsync(string to, string subject)
    {
        Sent.Add((to, subject));
        return Task.CompletedTask;
    }
}

EmailSpy email = new EmailSpy();

WelcomeService morning = new WelcomeService(
    email, new FixedClock(new DateTimeOffset(2026, 3, 1, 9, 0, 0, TimeSpan.Zero)));

WelcomeService afternoon = new WelcomeService(
    email, new FixedClock(new DateTimeOffset(2026, 3, 1, 15, 0, 0, TimeSpan.Zero)));

Console.WriteLine(await morning.WelcomeAsync("Ada"));
Console.WriteLine(await afternoon.WelcomeAsync("Grace"));

Console.WriteLine("emails sent: " + email.Sent.Count);

foreach ((string to, string subject) in email.Sent)
{
    Console.WriteLine("  " + to + " -> " + subject);
}

Output:

Good morning
Good afternoon
emails sent: 2
  Ada@example.test -> Good morning, Ada
  Grace@example.test -> Good afternoon, Grace

Every testable design decision is visible in that snippet. WelcomeService takes its collaborators as constructor parameters, so a test can hand it different ones; a version that wrote new SmtpEmailSender() inside WelcomeAsync would be untestable without a mail server. Dependency injection is a testability property first and an architecture fashion second.

The fixed clock removes an entire category of flake. A test asserting "Good morning" against DateTimeOffset.UtcNow passes all morning and fails after lunch — the classic suite that is red only on the afternoon build. Freezing time also lets you test the parts of the day nobody is at work for, such as the midnight rollover and the hour that a daylight-saving change deletes.

The spy answers a question no return value can. WelcomeAsync returns the greeting, so a plain assertion covers what it computed — but "did it send an email, to the right address, once" is an interaction, and only a recording double can see it. Notice that the two WelcomeService instances share one spy, which is why its Sent list holds both messages in call order.

Both doubles are under ten lines, which is the point: reach for a mocking library when an interface is wide or the scripting is intricate, not by reflex. A hand-written double is a normal class you can debug, step through and read.


Technical Depth: Five Kinds Of Stand-In

KindBehaviourFails the test when
DummyPassed to satisfy a parameter, never usedNever — if it is touched, your test is wrong about the code
StubReturns canned answersNever; assertions are about the result, not the stub
SpyRecords the calls it receivedYou assert afterwards on the record
MockHolds expectations up frontThe call does not match, sometimes at the moment it happens
FakeA real, simplified implementationBehaves like the real thing; assertions are about its state

The distinction that matters day to day is spy versus mock. A spy lets the code run to completion and then answers questions about it, so a failure message describes the finished behaviour. A strict mock objects mid-flight, which finds surprises earlier but produces tests that break on any refactor that reorders harmless calls.

"Fake" is the most under-used of the five. An in-memory repository that really stores and really queries lets a dozen tests assert on state — "after two orders, two rows" — which is far more durable than asserting that AddAsync was called twice.

Hand-rolled versus a library

Hand-rolledMoq / NSubstitute / FakeItEasy
Setup costA class per interfaceOne line per double
Wide interfacesPainful — every member needs a bodyFree; unset members return defaults
DebuggableYes; set a breakpoint in itGenerated at run time; harder to inspect
Reusable across testsYes, and it can grow useful helpersRe-scripted per test
Compile-time safety after a refactorThe compiler finds every doubleIt.IsAny arguments often still compile
Best forFakes and spies you use repeatedlyOne-off stubs, wide interfaces, strict verification

A practical rule: hand-roll the two or three doubles that appear in dozens of tests, and use a library for the long tail.

Moq, in the shape you will actually use it

using Moq;

Mock<IPaymentGateway> gateway = new Mock<IPaymentGateway>(MockBehavior.Strict);

gateway
    .Setup(g => g.ChargeAsync(750, It.IsAny<string>()))
    .ReturnsAsync(new PaymentResult(true, "AUTH-OK"));

Checkout checkout = new Checkout(orders, gateway.Object, audit, TimeProvider.System);

// ... act ...

gateway.Verify(g => g.ChargeAsync(750, "tok_live"), Times.Once);
gateway.VerifyNoOtherCalls();
Moq memberDoes
Setup(...).Returns(x)Canned return value
.ReturnsAsync(x)Same for a Task<T>-returning member
.Throws<T>()Simulate a failure — the case nobody tests
.Callback(...)Run code on the call, e.g. capture an argument
SetupSequence(...)Different answers on successive calls, for retry logic
Verify(..., Times.Never)Assert something did not happen
It.Is<T>(x => ...)Match arguments by predicate
MockBehavior.StrictAny unconfigured call throws immediately
.ObjectThe double you pass to the code under test
VerifyNoOtherCalls()Nothing beyond what you verified occurred

MockBehavior.Loose is the default and it is quietly permissive: unconfigured methods return null, 0 or default, so a test can pass while the code takes a path you never intended. Strict mocks are noisier and catch more.

NSubstitute expresses the same ideas without the lambda wrapper:

using NSubstitute;

IPaymentGateway gateway = Substitute.For<IPaymentGateway>();

gateway.ChargeAsync(750, Arg.Any<string>())
       .Returns(Task.FromResult(new PaymentResult(true, "AUTH-OK")));

// ... act ...

await gateway.Received(1).ChargeAsync(750, "tok_live");
await gateway.DidNotReceive().ChargeAsync(0, Arg.Any<string>());

What not to replace

  • Types you do not own. HttpClient, DbContext and ILogger<T> are large, and a double of one encodes your guess about its behaviour. Wrap them in an interface of your own — or, better, substitute at the seam they already provide.
  • HttpClient has such a seam: HttpMessageHandler. Replace that and the real client, with its real header and content handling, stays in the test.
sealed class StubHandler : HttpMessageHandler
{
    private readonly HttpStatusCode _status;
    private readonly string _body;

    public StubHandler(HttpStatusCode status, string body)
    {
        _status = status;
        _body = body;
    }

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken) =>
        Task.FromResult(new HttpResponseMessage(_status)
        {
            Content = new StringContent(_body, Encoding.UTF8, "application/json")
        });
}
  • ILogger<T>. Verifying log calls couples tests to wording nobody promised. Pass NullLogger<T>.Instance and forget it — unless the log is the feature, in which case log through your own audit interface, as the example below does.
  • The system clock. .NET 8 added TimeProvider: inject it, pass TimeProvider.System in production, and use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing in tests, which can also advance time so that timer- and delay-based code runs instantly.
  • The type under test. Partial-mocking the class you are testing means the test proves something about a subclass that does not ship.
  • Value objects and DTOs. A record is cheap to construct for real. A double of one is pure ceremony.
DependencyReplace with
HttpClientThe real client over a stub HttpMessageHandler
DbContext / EF CoreSQLite in-memory, or a real database in an integration test
DateTime.UtcNowTimeProvider plus FakeTimeProvider
RandomA seeded instance, or your own IRandom
Guid.NewGuidAn IIdGenerator returning a fixed sequence
File systemA path under Path.GetTempPath(), or an abstraction if it is used widely
ILogger<T>NullLogger<T>.Instance

State or interaction?

Assert on state when the code's job is to compute or store something: the total, the saved row, the returned outcome. Assert on interaction when the effect leaves the process and there is nothing to inspect: an email sent, a card charged, a message published — and, most valuably, when the correct behaviour is that the call did not happen.

The failure mode of interaction assertions is over-specification. A test that pins down the exact number and order of five calls fails when a developer adds a harmless sixth, so the team learns to update the test without reading it. Verify the interactions that a user or an auditor would notice, and let the rest be free.


Real World Example: A Checkout With Four Stand-Ins

Placing an order touches money, storage, an audit trail and the clock. All four get stand-ins, and the scenarios below include the ones production actually hits: a decline, and a gateway that does not answer.

interface IOrderRepository
{
    Task<int> AddAsync(Order order);
}

interface IPaymentGateway
{
    Task<PaymentResult> ChargeAsync(int amountMinorUnits, string cardToken);
}

interface IAuditLog
{
    void Record(string message);
}

record CheckoutRequest(string Sku, int Quantity, int UnitMinorUnits, string CardToken);

record PaymentResult(bool Approved, string Code);

record Order(int Id, string Sku, int Quantity, int TotalMinorUnits, DateTimeOffset PlacedAt);

record CheckoutOutcome(string Status, int? OrderId, string Detail);

sealed class Checkout
{
    private readonly IOrderRepository _orders;
    private readonly IPaymentGateway _payments;
    private readonly IAuditLog _audit;
    private readonly TimeProvider _clock;

    public Checkout(
        IOrderRepository orders, IPaymentGateway payments, IAuditLog audit, TimeProvider clock)
    {
        _orders = orders;
        _payments = payments;
        _audit = audit;
        _clock = clock;
    }

    public async Task<CheckoutOutcome> PlaceAsync(CheckoutRequest request)
    {
        int total = request.UnitMinorUnits * request.Quantity;

        if (request.Quantity < 1 || request.UnitMinorUnits < 1)
        {
            _audit.Record("rejected " + request.Sku + " total=" + total);
            return new CheckoutOutcome("rejected", null, "quantity and price must be positive");
        }

        PaymentResult payment;

        try
        {
            payment = await _payments.ChargeAsync(total, request.CardToken);
        }
        catch (Exception ex)
        {
            _audit.Record("payment error " + ex.GetType().Name);
            return new CheckoutOutcome("error", null, ex.GetType().Name);
        }

        if (!payment.Approved)
        {
            _audit.Record("declined " + payment.Code);
            return new CheckoutOutcome("declined", null, payment.Code);
        }

        int id = await _orders.AddAsync(
            new Order(0, request.Sku, request.Quantity, total, _clock.GetUtcNow()));

        _audit.Record("placed order=" + id + " total=" + total);
        return new CheckoutOutcome("placed", id, payment.Code);
    }
}

The four doubles, one of each useful kind:

// FAKE: really stores, really assigns ids, just not in a database.
sealed class InMemoryOrders : IOrderRepository
{
    private readonly List<Order> _saved = new();

    public int Count => _saved.Count;

    public Order? Last => _saved.Count == 0 ? null : _saved[^1];

    public Task<int> AddAsync(Order order)
    {
        int id = _saved.Count + 1;
        _saved.Add(order with { Id = id });
        return Task.FromResult(id);
    }
}

// STUB + SPY: scripted answers, and a record of every amount it was asked to charge.
sealed class ScriptedGateway : IPaymentGateway
{
    private readonly Queue<Func<PaymentResult>> _script;

    public ScriptedGateway(params Func<PaymentResult>[] script) =>
        _script = new Queue<Func<PaymentResult>>(script);

    public List<int> Charges { get; } = new();

    public Task<PaymentResult> ChargeAsync(int amountMinorUnits, string cardToken)
    {
        Charges.Add(amountMinorUnits);

        // A double that refuses to improvise catches accidental retry loops.
        if (_script.Count == 0)
        {
            throw new InvalidOperationException("gateway called more times than scripted");
        }

        return Task.FromResult(_script.Dequeue()());
    }
}

// SPY: the audit trail, kept in a list.
sealed class AuditSpy : IAuditLog
{
    public List<string> Messages { get; } = new();

    public void Record(string message) => Messages.Add(message);
}

// STUB: time stands still.
sealed class FrozenClock : TimeProvider
{
    private readonly DateTimeOffset _now;

    public FrozenClock(DateTimeOffset now) => _now = now;

    public override DateTimeOffset GetUtcNow() => _now;
}

Each scenario builds its own doubles — the same discipline xUnit enforces with a fresh class instance per test:

DateTimeOffset placedAt = new DateTimeOffset(2026, 2, 14, 10, 30, 0, TimeSpan.Zero);
CheckoutRequest threeBolts = new CheckoutRequest("bolt", 3, 250, "tok_live");

await Scenario("approved      ",
    new ScriptedGateway(() => new PaymentResult(true, "AUTH-OK")), threeBolts);

await Scenario("declined      ",
    new ScriptedGateway(() => new PaymentResult(false, "INSUFFICIENT_FUNDS")), threeBolts);

await Scenario("gateway down  ",
    new ScriptedGateway(() => throw new TimeoutException()), threeBolts);

await Scenario("bad quantity  ",
    new ScriptedGateway(() => new PaymentResult(true, "AUTH-OK")), threeBolts with { Quantity = 0 });

async Task Scenario(string label, ScriptedGateway gateway, CheckoutRequest request)
{
    InMemoryOrders orders = new InMemoryOrders();
    AuditSpy audit = new AuditSpy();
    Checkout checkout = new Checkout(orders, gateway, audit, new FrozenClock(placedAt));

    CheckoutOutcome outcome = await checkout.PlaceAsync(request);

    string charges = gateway.Charges.Count == 0 ? "none" : string.Join(",", gateway.Charges);
    string at = orders.Last?.PlacedAt.UtcDateTime.ToString("s") ?? "-";

    Console.WriteLine(label + outcome.Status
        + "  order=" + (outcome.OrderId?.ToString() ?? "-")
        + "  detail=" + outcome.Detail);

    Console.WriteLine("    charges=" + charges + "  saved=" + orders.Count + "  at=" + at
        + "  audit=" + string.Join(" / ", audit.Messages));
}

Output:

approved      placed  order=1  detail=AUTH-OK
    charges=750  saved=1  at=2026-02-14T10:30:00  audit=placed order=1 total=750
declined      declined  order=-  detail=INSUFFICIENT_FUNDS
    charges=750  saved=0  at=-  audit=declined INSUFFICIENT_FUNDS
gateway down  error  order=-  detail=TimeoutException
    charges=750  saved=0  at=-  audit=payment error TimeoutException
bad quantity  rejected  order=-  detail=quantity and price must be positive
    charges=none  saved=0  at=-  audit=rejected bolt total=0

The most valuable line in that transcript is charges=none. Three of the four scenarios prove that something happened; the last proves that something did not, and it is the only assertion that can catch a future refactor which moves the guard clause below the charge. A validation bug that returns the right error message while still taking the customer's money is not a cosmetic bug, and no assertion about the returned CheckoutOutcome would notice it.

saved=0 on the declined and error rows is a state assertion, and it is deliberately not phrased as "AddAsync was never called". The fake really stores, so the test asks the question a support engineer would ask — is there an order in the table? — and it keeps working if the service later saves through a different method, a batch, or a unit of work.

The gateway down scenario is the one most suites are missing. Production failures are dominated by dependencies that hang, refuse or return nonsense, and a stub scripted to throw is the cheapest possible way to reach that catch. Note that the audit records ex.GetType().Name rather than ex.Message: types are yours to depend on, while a third-party client's message text can change in a patch release and take your assertions with it.

Two smaller details are load-bearing. at=2026-02-14T10:30:00 proves the service stamped the injected clock's time rather than reading the machine's, which is what makes the assertion possible at all. And ScriptedGateway throws when the script runs out, so an accidental retry loop fails loudly instead of silently returning the same approval twice — a double that refuses to improvise is a feature, and it is exactly what MockBehavior.Strict buys you from a library.

Rendered as a real test, the last scenario is four lines of arrangement and three assertions:

[Fact]
public async Task A_zero_quantity_is_rejected_before_the_card_is_charged()
{
    ScriptedGateway gateway = new ScriptedGateway(() => new PaymentResult(true, "AUTH-OK"));
    AuditSpy audit = new AuditSpy();
    Checkout checkout = new Checkout(
        new InMemoryOrders(), gateway, audit, new FrozenClock(_placedAt));

    CheckoutOutcome outcome = await checkout.PlaceAsync(_threeBolts with { Quantity = 0 });

    Assert.Equal("rejected", outcome.Status);
    Assert.Empty(gateway.Charges);
    Assert.Equal("rejected bolt total=0", Assert.Single(audit.Messages));
}

Common Mistakes

  1. Newing dependencies inside the method. new SmtpEmailSender() in the middle of a service makes the whole path untestable. Take collaborators as constructor parameters.
  2. Leaving the clock, Random or Guid.NewGuid un-injected. These produce tests that pass in the morning, or once in twenty runs, and they train the team to press retry.
  3. Loose mocks hiding a path. With MockBehavior.Loose, an unconfigured call returns null or 0 and your test quietly exercises a branch you never meant to reach.
  4. Verifying every call in order. Over-specified interaction tests fail on harmless refactors, so they get updated blindly. Verify what a user or an auditor would notice.
  5. Asserting on log or exception message text. Verify(logger => logger.Log(...)) and Assert.Equal("Object reference not set...", ex.Message) both break on wording nobody promised.
  6. Mocking HttpClient or DbContext directly. Use the seams they provide — a stub HttpMessageHandler, SQLite in-memory — so the real header, serialisation and query logic still runs.
  7. Never testing the failure paths. If no stub in the suite throws or declines, the catch blocks and compensations have never executed anywhere but production.
  8. Sharing one double across tests. A spy whose list carries over makes assertions depend on run order. Build the doubles in the constructor, which xUnit runs afresh for every test.

Best Practices

  • Replace only what is slow, non-deterministic or outward-facing. Money, mail, networks, clocks and randomness get stand-ins. Value objects, collections and your own pure logic run for real.
  • Prefer a fake to a mock where state can be observed. "Two rows after two orders" survives refactoring; "AddAsync called twice" does not.
  • Assert the negative on anything irreversible. Assert.Empty(gateway.Charges) or Verify(..., Times.Never) is the only test that catches a guard clause moving below the side effect.
  • Script the failures too. Every dependency deserves at least one test where it throws, times out or declines, because that is what it will eventually do.
  • Hand-roll the doubles you reuse; use a library for the long tail. A named InMemoryOrders grows helpers and reads well; a one-off stub for a wide interface is a single Substitute.For line.
  • Make doubles refuse to improvise. Running out of script, or receiving an unconfigured call, should fail the test rather than return default.
  • Inject TimeProvider, not DateTime.UtcNow. TimeProvider.System in production, FakeTimeProvider in tests, and delay-based code becomes instantaneous and exact.
  • Depend on your own abstractions at the edges. An IPaymentGateway you defined is safe to double; a third-party client class you doubled encodes your guesses about someone else's behaviour.

Practice Exercises

  1. Spy on a negative. Write an InvoiceService that emails a receipt only when payment is approved. Using a hand-rolled EmailSpy, write two tests: one asserting exactly one email on approval, and one asserting Assert.Empty on decline. Then move the send above the approval check and confirm which test catches it.
  2. A fake with real behaviour. Build InMemoryCustomerRepository that enforces a unique email, assigns sequential ids and returns copies rather than references. Write tests proving that a duplicate email throws and that mutating a returned customer does not change the stored one — the second is a bug your fake should make impossible.
  3. Stub the transport, not the client. Test a WeatherClient built on a real HttpClient by passing a stub HttpMessageHandler that returns a fixed JSON body, then a 500, then a body with a missing field. Assert the parsed result, the thrown exception type and the fallback, without any network access.
  4. Time under control. Add TimeProvider to a SessionService that expires sessions after 30 minutes. Using FakeTimeProvider and its Advance method, prove the 29-minute, exactly-30-minute and 31-minute cases, and confirm the whole test class runs in milliseconds with no Task.Delay.