📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are the different kinds of test doubles (dummy, stub, fake, mock, spy), and when would you write a hand-rolled fake instead of using a mocking library?

The five kinds of test double (dummy, stub, fake, mock, spy), how they differ in state versus interaction verification, and when a hand-rolled fake beats a mocking library in .NET 10 tests.

Junior Coding Intermediate fakes mocking nsubstitute test-doubles testing unit-testing

🎯 Key points

  • Dummy: passed only to satisfy a signature, never used
  • Stub: canned answers to drive the code down a path; no assertions on it
  • Fake: a working, simplified implementation (in-memory repository); you assert on its state, not its calls
  • Mock: set expectations on calls and verify them (interaction or behaviour verification)
  • Spy: records calls so you assert afterwards; NSubstitute's Received() is spy-style
  • Prefer state verification; use mocks only when the call itself is the outcome (email sent, message published)
  • Hand-roll a fake for stateful dependencies used by many tests; Microsoft ships FakeTimeProvider and FakeLogger

⏱ 30-second answer

These are Gerard Meszaros's five test doubles:

  • A dummy only fills a parameter and is never used.
  • A stub returns canned answers so the code takes a particular path.
  • A fake is a simplified implementation that really works, such as an in-memory repository. You check its state, not the calls made on it.
  • A mock is set up with expected calls and then verifies the interaction. A spy records calls so you can assert on them afterwards.

I hand-roll a fake when the dependency holds state and many tests use it. Microsoft already ships two: FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) and FakeLogger (Microsoft.Extensions.Diagnostics.Testing). One small class replaces dozens of fragile mock setups. The trade-off is that a fake is code you maintain. Mocks cost nothing to write, but they break whenever the implementation changes.

🗣 Full answer (senior)

How I would answer this in an interview

"The vocabulary comes from Gerard Meszaros. A dummy is passed just so the code compiles, like a logger nobody reads. A stub gives canned answers: 'when GetRate is called, return 1.5', so the code goes down the path I'm testing. I never assert on a stub. A fake really works but takes a shortcut: an in-memory repository backed by a dictionary, or Microsoft's FakeTimeProvider that lets me move the clock forward. A mock is about interaction. I state which calls I expect and the test fails if they don't happen. A spy is the record-then-assert version of that. NSubstitute's Received() is spy-style, because you check afterwards.

The important split is state verification versus interaction verification. With a stub or a fake I check the result: the order total, or what's in the fake repository. With a mock I check that a call was made. I prefer state verification because it survives refactoring. I only verify interactions when the call is the outcome, like 'an email was sent' or 'a message was published to Service Bus'.

I write a fake by hand when the dependency is stateful and lots of tests use it. Say a repository where tests add an order and then read it back. Mocking that means setting up Add and GetById to cooperate in every single test. A 30-line InMemoryOrderRepository does it once, and it behaves like the real thing. The mistake I see is mocking everything, so the tests describe the implementation line by line and every refactor breaks fifty of them."


The five doubles

Double What it does You assert on Typical .NET example
Dummy Fills a parameter Nothing NullLogger<T>.Instance
Stub Returns canned values The system under test's result rates.GetRate("AUD").Returns(1.5m)
Fake Simplified working implementation The fake's state InMemoryOrderRepository, FakeTimeProvider
Mock Expected calls, verified The calls (behaviour) Moq Verify(x => x.Send(...), Times.Once())
Spy Records calls The calls, after the fact NSubstitute Received(1).Send(...), FakeLogger.Collector

Hand-rolled fake or mocking library?

Use a library stub or mock when Hand-roll a fake when
One or two calls, no state The dependency holds state between calls
The interaction is the outcome Many tests (say more than five) set up the same behaviour
The interface is large and you need one method You want the double to enforce real rules (unique keys, not found)
It's a quick, single-use test Microsoft already ships one (FakeTimeProvider, FakeLogger)

Licences

NSubstitute (BSD 3-clause), Moq (BSD 3-clause) and FakeItEasy (MIT) are all free to use. Moq briefly shipped the SponsorLink analyser in version 4.20.0 in August 2023 and removed it in 4.20.2 after the backlash. Some organisations moved to NSubstitute because of that. A hand-rolled fake has no licence question at all.

Production example

In a typical order service with around 120 handler tests that each mocked the repository's Add, GetById and SaveChangesAsync, renaming one repository method breaks every one of them. Swapping the mocks for a single in-memory fake cuts the setup code by hundreds of lines, and the same rename touches one file.

🔍 What the interviewer is checking

Checks the candidate knows the test double vocabulary and can pick the simplest double, preferring state verification over checking calls.

Green flags

  • Defines all five and separates state verification from interaction verification.
  • Says mocks are for when the call is the outcome, and knows mock-heavy tests break on refactoring.
  • Gives a concrete reason to hand-roll a fake (stateful, reused, enforces invariants).
  • Knows FakeTimeProvider and FakeLogger exist.

Red flags

  • Uses "mock" for everything and verifies every call.
  • Mocks DbContext, HttpClient or DateTime.Now directly.
  • Has never written a fake, or thinks fakes are always over-engineering.

📚 Learn in depth

1. Why test doubles exist

A unit test should be fast, deterministic and focused on one piece of logic. Real dependencies (a database, the clock, an HTTP API) are slow, non-deterministic or both. A test double stands in for one of those dependencies through a seam, usually an interface injected through the constructor.

      Test
       │ arrange: create double
       ▼
  OrderService ──▶ IOrderRepository ◀── InMemoryOrderRepository (fake)
       │       ──▶ IEmailSender     ◀── Substitute.For<IEmailSender>() (spy)
       │       ──▶ TimeProvider     ◀── FakeTimeProvider (fake)
       ▼
  assert: state of result + fake, and calls on the spy

2. State verification versus behaviour verification

Martin Fowler's Mocks Aren't Stubs draws this line. State verification checks what the system ended up with. Behaviour verification checks which calls the system made. Behaviour verification couples the test to how the code works, so it breaks on refactoring even when the result is unchanged. Use it when the side effect is the result, like a sent email, a published event or a charged card.

3. How mocking libraries work

NSubstitute, Moq and FakeItEasy all generate a proxy class at runtime with Castle DynamicProxy. That's why they can only intercept interfaces and virtual members, not sealed classes or static methods. Each call is recorded and matched against your configured rules (Returns, Setup). Verification walks the recorded calls. Because the proxies are generated with Reflection.Emit, these libraries don't work under Native AOT. Hand-rolled fakes do.

4. Fakes Microsoft ships

  • FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing): Advance(TimeSpan) moves the clock and fires timers that are due, so Task.Delay(timeProvider, ...) and PeriodicTimer become deterministic.
  • FakeLogger<T> (Microsoft.Extensions.Diagnostics.Testing): records every log entry in Collector, so you can check that a warning was logged without mocking ILogger.Log and its generic state.
  • FakeHttpMessageHandler-style handlers: not shipped, but a 10-line DelegatingHandler subclass is the standard fake for HttpClient.

5. Keeping a fake honest

A fake can drift away from the real implementation. The fix is a contract test: one abstract test class with the behaviour (add, then get; get a missing id returns null; duplicate key throws), run against both the fake and the real EF Core repository on Testcontainers. If both pass, the fake is trustworthy.

Try it yourself

  1. Write an OrderService test with NSubstitute stubs for Add and GetById, then the same test with an in-memory fake. Compare the line counts.
  2. Rename a repository method and count how many tests break in each style.
  3. Use FakeLogger<OrderService> to assert that a warning was logged when stock runs out.
  4. Write one abstract contract test class and run it against your fake and a SQLite or Testcontainers repository.
  5. Try mocking a sealed class with NSubstitute and read the error. Explain why it happens.

💻 Code

A hand-rolled fake for stateful data, a library spy for the side effect, and Microsoft's FakeTimeProvider for time (xUnit v3, NSubstitute).

#nullable enable
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using Xunit;

namespace Orders.Tests;

// ----- Code under test -----
public sealed record Order(Guid Id, string CustomerEmail, decimal Total, DateTimeOffset PlacedAt);

public interface IOrderRepository
{
    Task AddAsync(Order order, CancellationToken ct);
    Task<Order?> GetAsync(Guid id, CancellationToken ct);
}

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

public sealed class OrderService(IOrderRepository orders, IEmailSender email, TimeProvider clock)
{
    public async Task<Guid> PlaceAsync(string customerEmail, decimal total, CancellationToken ct)
    {
        var order = new Order(Guid.NewGuid(), customerEmail, total, clock.GetUtcNow());
        await orders.AddAsync(order, ct);
        await email.SendAsync(customerEmail, $"Order {order.Id} received", ct);
        return order.Id;
    }
}

// ----- Hand-rolled fake: real behaviour, written once, reused by every test -----
public sealed class InMemoryOrderRepository : IOrderRepository
{
    private readonly Dictionary<Guid, Order> _orders = [];

    public Task AddAsync(Order order, CancellationToken ct)
    {
        // Enforces the same rule as the database's primary key.
        if (!_orders.TryAdd(order.Id, order))
            throw new InvalidOperationException($"Duplicate order {order.Id}");
        return Task.CompletedTask;
    }

    public Task<Order?> GetAsync(Guid id, CancellationToken ct) =>
        Task.FromResult(_orders.GetValueOrDefault(id));
}

// ----- Tests -----
public sealed class OrderServiceTests
{
    private readonly InMemoryOrderRepository _orders = new();          // fake
    private readonly IEmailSender _email = Substitute.For<IEmailSender>(); // spy
    private readonly FakeTimeProvider _clock =
        new(new DateTimeOffset(2026, 11, 21, 9, 0, 0, TimeSpan.Zero)); // fake clock

    [Fact]
    public async Task Placed_order_is_stored_with_the_current_time()
    {
        var sut = new OrderService(_orders, _email, _clock);
        var ct = TestContext.Current.CancellationToken;

        var id = await sut.PlaceAsync("[email protected]", 42m, ct);

        // State verification: we check what was stored, not which calls were made.
        var stored = await _orders.GetAsync(id, ct);
        Assert.NotNull(stored);
        Assert.Equal(42m, stored.Total);
        Assert.Equal(_clock.GetUtcNow(), stored.PlacedAt);
    }

    [Fact]
    public async Task Customer_is_emailed_once()
    {
        var sut = new OrderService(_orders, _email, _clock);
        var ct = TestContext.Current.CancellationToken;

        await sut.PlaceAsync("[email protected]", 42m, ct);

        // Interaction verification is right here: the email IS the outcome.
        await _email.Received(1).SendAsync("[email protected]", Arg.Is<string>(s => s.StartsWith("Order ")), ct);
    }
}

⚠ Common mistakes

  • Mistake: Calling every double a "mock". Why it is wrong: It hides the key choice between state and interaction verification, and leads to verifying calls that don't matter. Instead: Use the right word, and verify calls only when the call is the outcome.
  • Mistake: Asserting on a stub (Received() on a query method that only returns data). Why it is wrong: It couples the test to the implementation. If the code caches the value, the test fails even though behaviour is correct. Instead: Assert on the result the stub drives.
  • Mistake: Mocking a stateful repository with Setup for Add and Get in every test. Why it is wrong: The setups get copied around, drift apart and break together on a rename. Instead: Write one in-memory fake.
  • Mistake: Writing a fake with no rules (no duplicate-key check, no not-found case). Why it is wrong: Tests pass against the fake, then fail against the real database. Instead: Copy the important invariants into the fake and keep it honest with a shared contract test.
  • Mistake: Mocking DateTime.Now with a custom IClock in new code. Why it is wrong: .NET 8 and later already ship TimeProvider, and FakeTimeProvider also drives timers and Task.Delay. Instead: Inject TimeProvider and use FakeTimeProvider in tests.
  • Mistake: Mocking ILogger<T>.Log to check a message. Why it is wrong: The generic TState and formatter make the setups unreadable and fragile. Instead: Use FakeLogger<T> and inspect Collector.LatestRecord.
  • Mistake: Mocking types you don't own, like DbContext or HttpClient. Why it is wrong: You encode your guess about how they behave. Instead: Use a real database in a container, or a fake HttpMessageHandler.

🏛 Senior insight: trade-offs

My rule of thumb: stub queries, verify commands, fake state. Queries (methods that return data) get stubs or fakes and I assert on the result. Commands with external side effects (send, publish, charge) get spies, and I verify them. Anything with state that many tests use gets a hand-rolled fake, kept honest by a contract test against the real implementation. That keeps tests about behaviour, so refactoring stays cheap.

The cost of a fake is real but small: a class to maintain, plus the contract test. I measure the alternative by counting how many tests break on a pure refactor. If a rename breaks more than a handful, the doubles are too tied to the implementation.

Option When it fits Cost When not to
Library stub (NSubstitute Returns) One-off canned answer Seconds to write; tied to method signatures Same setup copied across many tests
Library mock or spy (Received, Verify) Side effect is the outcome Breaks if the call shape changes Query methods; internal collaborators
Hand-rolled fake Stateful dependency shared by many tests A class plus a contract test Huge interfaces you barely use
Microsoft fakes (FakeTimeProvider, FakeLogger) Time, timers, logging A package reference Never avoid them for a home-made version
Real dependency (Testcontainers) Behaviour depends on the real engine (SQL, transactions) Seconds of start-up Pure business logic

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about asserting on large results instead of calls. Why: Checks they know snapshot testing as another way to assert on state.
    How to answer

    Use snapshot testing when the output is large or structured and you care about all of it: an API response, a generated email, source generator output, an OpenAPI document. Verify serialises the result to a .verified.txt file that is committed with the code. On the next run it compares the new output and, if anything differs, writes a .received.txt file, fails the test and shows a diff.

    Verify scrubs volatile values such as Guids and dates by default. When a change is intended, you review the diff and accept it, and the updated snapshot is reviewed again in the pull request.

    I keep explicit assertions for the one or two values that are the business rule, such as "GST is 10%". The trade-off is that snapshots replace a lot of assertion code, but if people accept them without reading, they only detect change. They stop checking correctness.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me