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

📚 Interview question

What is the difference between a stub and a mock? Explain state verification versus behaviour verification, the classicist and mockist schools, and how that choice affects your .NET tests.

Covers stubs versus mocks, state versus behaviour (interaction) verification, classicist versus mockist TDD, and how each choice shapes NSubstitute-based tests in .NET.

Junior Theory Intermediate mocking nsubstitute stubs test-doubles testing unit-testing

🎯 Key points

  • A stub only supplies predefined answers so the SUT can run; the test never asserts on it
  • A mock exists to verify that the SUT made a specific call to a collaborator
  • State verification checks the result or state; behaviour verification checks calls made
  • Classicist (Detroit) style uses real objects and fakes, mocking only awkward boundaries
  • Mockist (London) style mocks every collaborator to isolate the class
  • Verify interactions only when the call itself is the outcome (email sent, message published)
  • Mocks couple tests to call shape: readability and refactor-resistance drop as they spread
  • Mocking libraries (NSubstitute, Moq, FakeItEasy) can create either; the role is in how you use it

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The words get used loosely, so I go by role. A stub is a stand-in that answers questions: when my OrderService asks the IPriceCatalogue for 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 that IEmailSender.SendAsync was called once with the customer's address. In NSubstitute the same Substitute.For<T>() object can play either role; it becomes a mock the moment I call Received() 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 vs mock

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 vs mockist

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

When to verify a call

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands what a test double is for, not just how to call a mocking library.

Green flags

  • Defines stub as input, mock as verified output
  • Names state vs behaviour verification and the two schools
  • Verifies only commands with business meaning
  • Mentions brittleness on refactoring

Red flags

  • Uses "mock" for everything
  • Verifies every dependency call by default
  • Mocks DTOs or the class under test

📚 Learn in depth

1. Meszaros' vocabulary

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)

2. Direct input vs indirect output

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.

3. How a mocking library builds a double

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.

4. Why mock-heavy tests are brittle

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.

5. Licensing note

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.

Try it yourself

  1. Write a test for an OrderService that verifies a repository Get call with Received(). Refactor to cache the result and watch it fail with no behaviour change.
  2. Rewrite it as a stub plus an assert on the returned value; repeat the refactor.
  3. Write a test that checks a confirmation email is sent, first with Received(), then with a hand-written spy that collects sent messages.
  4. Try Substitute.For<SomeSealedClass>() and read the error to see the proxy limitation.

💻 Code

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>());
    }
}

⚠ Common mistakes

  • Mistake: Calling every test double a "mock". Why it is wrong: It hides whether the test checks input or output, which decides how brittle it is. Instead: Name the role: stub for answers, mock for verified calls.
  • Mistake: Verifying calls on stubs (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.
  • Mistake: Verifying the exact order of internal calls. Why it is wrong: Order is rarely a requirement and changes with refactoring. Instead: Verify only side effects that matter to the business.
  • Mistake: Creating mocks or substitutes for value objects, DTOs or the class under test. Why it is wrong: You end up testing the mock setup, not the code, and these types are cheap to build. Instead: Instantiate real value objects and DTOs directly in the test; use doubles only for collaborators at a boundary.
  • Mistake: Using a mocking library for something that needs real behaviour, like a repository with queries. Why it is wrong: The setup grows huge and still doesn't behave like the real thing. Instead: A fake (in-memory implementation) or a real database via Testcontainers.
  • Mistake: Asserting on log text through a mocked 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions fakes, spies or dummies Why: Checks the full test double vocabulary and when to hand-roll a fake
    How to 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.

  2. When: Candidate mentions NSubstitute or Moq Why: Checks practical mocking syntax and awareness of the Moq SponsorLink episode
    How to answer

    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.

    • NSubstitute: 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>());.
    • Moq: 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.

  3. When: Candidate says mock-heavy tests are brittle Why: Checks they can spot over-mocking in a real code review
    How to answer

    Ranked by severity:

    1. Tests that can't fail: an async void test and a try/catch that swallows the assertion exception give false greens.
    2. Shared static list: results depend on order and parallelism, so tests are flaky and can assert on another test's data.
    3. Thread.Sleep(3000): slow (3 s each) and still flaky on a busy CI agent. Await a completion signal instead.
    4. DateTime.Now: time-dependent logic is untestable at boundaries. Inject TimeProvider and use FakeTimeProvider.
    5. Mocking everything, including DbContext: tests check call sequences, not behaviour, and break on every refactor.
    6. Exact log-text assertions: brittle. Use 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.

↩ Usually asked after

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me