Covers stubs versus mocks, state versus behaviour (interaction) verification, classicist versus mockist TDD, and how each choice shapes NSubstitute-based tests in .NET.
A stub feeds the code under test canned answers ("the price service returns 10") and the test never checks it. A mock records how it was called, and the test asserts on those calls ("the email sender was called once with this address").
That maps to two ways of verifying: state verification checks the result or state after the Act; behaviour verification checks the interactions. The classicist school prefers state checks with real objects or fakes; the mockist school mocks every collaborator.
My default is classicist: stub queries, and verify calls only when the call is the outcome, like publishing a message. The trade-off: mock-heavy tests isolate well but break whenever internals are refactored.
"The words get used loosely, so I go by role. A stub is a stand-in that answers questions: when my
OrderServiceasks theIPriceCataloguefor a price, the stub returns 10. I never assert on a stub. A mock is a stand-in I check: after the Act, I assert thatIEmailSender.SendAsyncwas called once with the customer's address. In NSubstitute the sameSubstitute.For<T>()object can play either role; it becomes a mock the moment I callReceived()on it.That gives two verification styles. State verification asks 'what is the result?': the returned total, the saved row, the order status. Behaviour verification asks 'what did it call?'. Martin Fowler's 'Mocks Aren't Stubs' describes two schools around this. Classicists, the Detroit school, use real collaborators where they can, fakes for slow things like the database, and check state. Mockists, the London school, mock every collaborator and check interactions, which drives out interfaces as you design from the outside in.
In .NET services I lean classicist. Queries get stubs, because how the code fetched a value is an implementation detail. I only verify interactions when the side effect is the requirement and has no state I can observe: an email sent, a message published to Service Bus, a payment captured. The mistake I see is
Received()on every dependency, including the ones that only return data. Those tests pin the implementation, so a harmless refactor turns fifty tests red. Stub what you ask, verify only what you tell."
| Stub | Mock | |
|---|---|---|
| Purpose | Provide input to the SUT | Check output the SUT sends |
| Test asserts on it? | Never | Yes (Received, Verify) |
| Typical target | Queries: repositories, catalogues, clocks | Commands: email, message bus, payment gateway |
| Breaks on refactor? | Rarely | Often, if overused |
| Classicist (Detroit) | Mockist (London) | |
|---|---|---|
| Unit of isolation | A behaviour, maybe several classes | One class |
| Collaborators | Real objects, fakes for I/O | Mocks for every dependency |
| Verification | Mostly state | Mostly interactions |
| Strength | Refactor-resistant tests | Pinpoints the failing class, drives interface design |
| Weakness | A bug can turn several tests red | Brittle; tests mirror the code |
| Verify | Don't verify |
|---|---|
IEmailSender.SendAsync for a confirmation email |
IRepository.GetByIdAsync that supplied data |
IPublisher.PublishAsync(OrderPlaced) |
ILogger.Log text (use FakeLogger if logging is a requirement) |
IPaymentGateway.CaptureAsync amount |
The order of internal calls |
On an order service, [a team I worked with] had about 600 unit tests where every dependency was a verified mock. Splitting one repository method into two turned 140 tests red without any behaviour change. Rewriting the worst offenders to stub queries and assert on returned state cut red-on-refactor failures to a handful and kept the same mutation score.
Checks whether the candidate understands what a test double is for, not just how to call a mocking library.
Green flags
Red flags
Gerard Meszaros (xUnit Test Patterns) named five test doubles. This question is about the two that matter most:
Dummy - passed but never used
Stub - returns canned answers (input to SUT)
Spy - stub that also records calls (inspect afterwards)
Mock - pre-programmed expectations (verify interactions)
Fake - working lightweight implementation (in-memory repo)
Think of the SUT's dependencies as two kinds of traffic:
queries (indirect input)
Stub ───────────────────────────────▶ SUT
│
Mock ◀───────────────────────────────── │
commands (indirect output)
A stub controls indirect input: values the SUT asks for. A mock observes indirect output: calls the SUT makes to change the world. This is the same split as command-query separation: stub queries, verify commands.
NSubstitute, Moq and FakeItEasy generate a runtime proxy class with Castle DynamicProxy. Each interface member is intercepted; the library records the call and its arguments, then looks up a configured return value. That is why they can mock interfaces and virtual members only: sealed classes and non-virtual methods can't be overridden by a proxy.
Substitute.For<IPrices>()
└─ Castle.DynamicProxy emits class IPricesProxy : IPrices
Get(sku) -> record call -> find matching .Returns() -> return value
Received() simply searches the recorded calls.
A verified interaction is an assertion about how the code works. Any refactor that keeps the behaviour but changes the calls (merging two repository calls, adding a cache, reordering) breaks the test. State assertions survive those refactors because they only describe what happened.
As of late 2026, NSubstitute and FakeItEasy are BSD/MIT licensed. Moq is still widely used, but its 2023 SponsorLink episode (a closed-source analytics dependency that read developers' git email) made many teams standardise on NSubstitute. Check current status before choosing.
OrderService that verifies a repository Get call with Received(). Refactor to cache the result and watch it fail with no behaviour change.Received(), then with a hand-written spy that collects sent messages.Substitute.For<SomeSealedClass>() and read the error to see the proxy limitation.Stub the query, verify only the command whose call is the requirement.
#nullable enable
namespace Billing.Tests;
using NSubstitute;
using Xunit;
public interface IPriceCatalogue { Task<decimal> GetPriceAsync(string sku, CancellationToken ct); }
public interface IInvoiceSender { Task SendAsync(string email, decimal total, CancellationToken ct); }
public sealed class InvoiceService(IPriceCatalogue prices, IInvoiceSender sender)
{
public async Task<decimal> BillAsync(string email, string sku, int qty, CancellationToken ct)
{
var total = await prices.GetPriceAsync(sku, ct) * qty;
await sender.SendAsync(email, total, ct);
return total;
}
}
public sealed class InvoiceServiceTests
{
private readonly IPriceCatalogue _prices = Substitute.For<IPriceCatalogue>(); // stub role
private readonly IInvoiceSender _sender = Substitute.For<IInvoiceSender>(); // mock role
[Fact]
public async Task BillAsync_ReturnsPriceTimesQuantity()
{
_prices.GetPriceAsync("SKU-1", Arg.Any<CancellationToken>()).Returns(10m);
var sut = new InvoiceService(_prices, _sender);
var total = await sut.BillAsync("[email protected]", "SKU-1", 3, CancellationToken.None);
// State verification: no Received() on the price stub
Assert.Equal(30m, total);
}
[Fact]
public async Task BillAsync_SendsInvoiceToCustomer()
{
_prices.GetPriceAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(10m);
var sut = new InvoiceService(_prices, _sender);
await sut.BillAsync("[email protected]", "SKU-1", 3, CancellationToken.None);
// Behaviour verification: the send IS the requirement
await _sender.Received(1).SendAsync("[email protected]", 30m, Arg.Any<CancellationToken>());
}
}
Received() on a repository Get). Why it is wrong: It pins the implementation; a cache or merged query breaks the test. Instead: Assert on the result the data produced.ILogger. Why it is wrong: LogInformation is an extension method, so you verify Log<TState> internals and break on wording changes. Instead: FakeLogger from Microsoft.Extensions.Diagnostics.Testing when logging is a real requirement.The stub/mock distinction is really about what the test couples to. A state assertion couples to the contract; an interaction assertion couples to the implementation. I want as many tests as possible to survive a refactor, so I reserve interaction checks for outgoing commands at the edge of the system, and even there a hand-written spy or fake is often clearer than a mocking DSL.
The choice also has a long-term cost that shows up in year two, not week one. A mockist suite mirrors today's class structure, so every redesign carries a test-rewrite tax and teams start avoiding refactors. A classicist suite reads more like a specification, which helps reviewers and new team members, at the price of less precise failure location. I pick per area: mockist-style checks at integration edges (bus, email, payments), classicist everywhere else, and I measure it by how many tests go red on behaviour-preserving refactors.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Stub (library or hand-written) | Supplying query results | Very low | Never wrong for inputs |
Mock with Received() |
Outgoing command is the requirement | Couples test to call shape | Queries, internal collaborators |
| Spy (records calls, assert later) | Several messages, readable asserts | A small class | When a library one-liner is clear enough |
| Fake | Stateful dependency (repo, cache) | Must be kept correct | When a real container is cheap enough |
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.
A mock library generates a runtime implementation of an interface or virtual members so a unit test can exercise the class under test in isolation from slow or non-deterministic dependencies: you control what each dependency returns and check the calls that matter.
var repo = Substitute.For<IOrderRepository>();, repo.GetAsync(42, Arg.Any<CancellationToken>()).Returns(order);, then await repo.Received(1).SaveAsync(Arg.Is<Order>(o => o.Status == Paid), Arg.Any<CancellationToken>());.new Mock<T>(), Setup(...).ReturnsAsync(...), Verify(..., Times.Once) and mock.Object; MockBehavior.Strict throws on any call that was not set up.In August 2023 Moq 4.20.0 bundled SponsorLink, an analyser that read the developer's git email and sent a hash to a sponsorship service; after a backlash it was removed in 4.20.2. The lesson is supply-chain hygiene. The trade-off with mocks: they isolate logic quickly, but too many verifications couple tests to implementation.
Ranked by severity:
async void test and a try/catch that swallows the assertion exception give false greens.Thread.Sleep(3000): slow (3 s each) and still flaky on a busy CI agent. Await a completion signal instead.DateTime.Now: time-dependent logic is untestable at boundaries. Inject TimeProvider and use FakeTimeProvider.DbContext: tests check call sequences, not behaviour, and break on every refactor.FakeLogger and assert on level, event id and structured state.The rewrite tests behaviour through real collaborators, controls time and concurrency deterministically, and fakes only the true boundaries.
Last updated 23 Nov 2026.