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.
These are Gerard Meszaros's five test doubles:
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.
"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
FakeTimeProviderthat 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'sReceived()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
AddandGetByIdto cooperate in every single test. A 30-lineInMemoryOrderRepositorydoes 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."
| 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 |
| 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) |
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.
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.
Checks the candidate knows the test double vocabulary and can pick the simplest double, preferring state verification over checking calls.
Green flags
FakeTimeProvider and FakeLogger exist.Red flags
DbContext, HttpClient or DateTime.Now directly.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
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.
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.
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.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.
OrderService test with NSubstitute stubs for Add and GetById, then the same test with an in-memory fake. Compare the line counts.FakeLogger<OrderService> to assert that a warning was logged when stock runs out.sealed class with NSubstitute and read the error. Explain why it happens.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);
}
}
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.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.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.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.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.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 |
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.
Last updated 23 Nov 2026.