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

πŸ“š Interview question

What is over-mocking? Explain the difference between testing behaviour and testing implementation details, why mock-heavy tests break when you refactor, and how you would fix a suite like that.

Covers over-mocking, behaviour versus implementation-detail tests, why interaction-heavy tests are brittle under refactoring, and practical ways to move a .NET suite towards behaviour-focused tests.

Mid-Level Theory Intermediate mocking over-mocking refactoring test-design testing unit-testing

🎯 Key points

  • Over-mocking: mocking every collaborator, including ones with no I/O, and verifying their calls
  • Behaviour tests check observable outcomes through a public API; implementation tests check how the code did it
  • A good test fails when behaviour breaks and passes through behaviour-preserving refactors
  • Mock-heavy tests give false positives (red on refactor) and false negatives (green on real bugs in wiring)
  • Strategy: real objects in-process, fakes for state you own, mocks (NSubstitute, FakeItEasy) only for boundaries you don't own
  • Build the SUT from the app's real DI registrations (ServiceCollection or WebApplicationFactory) and override only boundary services
  • Spot it with numbers: setup-to-assert ratio, red-on-refactor count, Stryker.NET mutation score vs line coverage
  • Fix legacy suites incrementally: replace brittle clusters when you touch that code, delete tests that only restate it

⏱ 30-second answer

Over-mocking is mocking every collaborator of a class, even plain in-process ones, and verifying the calls between them. The tests end up describing how the code works rather than what it does.

That gives the worst of both worlds: false alarms when you refactor without changing behaviour, and missed bugs because the real collaborators never run together.

I test behaviour through a public API: a use case, a handler, or an HTTP endpoint, with real in-process objects and mocks or fakes only at boundaries I don't own (third-party HTTP, Service Bus, email, the clock).

The trade-off: broader tests point less precisely at the failing class, but they survive refactoring and catch integration bugs.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Over-mocking is when every dependency in a test is a mock, including things like a validator, a mapper or a domain service that have no I/O at all, and the asserts are mostly Received() or Verify() on those mocks. The test becomes a mirror of the implementation: 'the handler calls the validator, then the mapper, then the repository, then the publisher'. That is not a requirement; it's just today's code.

The cost shows up in two directions. First, false positives: I merge two classes, or replace the mapper with a source generator, behaviour is identical, and forty tests go red. People learn to 'fix the tests' by updating mock setups, which means the tests are no longer checking anything. Second, false negatives: because the validator and mapper are mocked, nobody tests them working together, so a mapping bug or a wrong validation rule sails through. For example, at [company] a handler suite had [about 200] tests and [over 90 percent] line coverage, but a renamed DTO property broke the response in production because the mapper was mocked in every test.

What I do instead: test a unit of behaviour, not a unit of code. For a MediatR-style handler, that means real validator, real mapper, real domain objects, a fake or real database, and mocks only for things at the process edge: a payment gateway, an email sender, Service Bus, TimeProvider. Often the best level is the HTTP endpoint through WebApplicationFactory. To fix an existing suite I don't rewrite it in one go; when a refactor breaks mock tests, I replace that cluster with a few behaviour tests and delete the rest. The test I want fails when the behaviour breaks, and only then."


Behaviour vs implementation tests

Behaviour test Implementation-detail test
Asserts on Return value, persisted state, HTTP response, message sent out Calls between internal classes, call order
Survives refactor? Yes Usually not
Catches wiring bugs? Yes No
Failure precision Use case or endpoint Exact class

What to mock

Mock or fake Use the real thing
Third-party HTTP APIs (WireMock.Net or a stub HttpMessageHandler) Validators, mappers, domain services
Message bus publish, email, SMS Value objects, DTOs, entities
TimeProvider (FakeTimeProvider) The database, in integration tests (Testcontainers)
Payment gateway ILogger (or FakeLogger when logging is a requirement)

Signs of over-mocking

Smell What it tells you
More mock setup lines than assert lines Testing wiring, not outcomes
Received() on query methods Pinning implementation
Received.InOrder everywhere Call order treated as a requirement
Tests break on every refactor, never on real bugs Tests coupled to structure

Production example

On [a customer onboarding service], we replaced [about 180] mock-based handler tests with [about 45] tests that went through real handlers and SQL Server in a container. Line coverage stayed around [85%], Stryker.NET's mutation score rose from [52%] to [74%], and the next major refactor (splitting a handler into two) needed [zero] test changes.

πŸ” What the interviewer is checking

Checks whether the candidate writes tests that support refactoring and catch real bugs, rather than tests that mirror the code.

Green flags

  • Defines behaviour vs implementation-detail tests clearly
  • Explains both false positives and false negatives of over-mocking
  • Mocks at process boundaries only
  • Has an incremental plan and a way to measure it

Red flags

  • "Every dependency must be mocked to be a unit test"
  • Treats coverage as the quality metric
  • Fixes red tests by updating mock setups

πŸ“š Learn in depth

1. Two kinds of coupling

Every test couples to something. The question is what:

Test ──couples to──▢ Contract (inputs, outputs, side effects)   -> stable
Test ──couples to──▢ Structure (classes, calls, order)          -> changes with every refactor

Refactoring is defined as changing structure without changing behaviour. A test coupled to structure cannot, by definition, support refactoring.

2. Why mock-heavy tests miss bugs

When every collaborator is a mock, each class is tested against your assumptions about its neighbours, encoded in setups like mapper.Map(x).Returns(y). If those assumptions are wrong (the real mapper drops a field, the real validator rejects valid input), every test still passes:

Handler test:   Validator(mock: OK) -> Mapper(mock: dto) -> Repo(mock) -> Publisher(mock)
Reality:        Validator(rejects!) -> Mapper(drops field!) -> ...

Nothing ever runs the real chain until production.

3. Units of behaviour

The "unit" in unit test was never meant to be "one class". Kent Beck and the classicist school treat a unit as a behaviour that is isolated from other tests (no shared state), not from other classes. A handler plus its validator and domain objects is a fine unit.

4. Where to draw the boundary

Use the process boundary as the line:

        your process                          outside
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚ endpoint -> handler -> domain β”‚ ──▢ payment API   (mock/stub)
  β”‚          -> validator, mapper β”‚ ──▢ Service Bus   (fake/mock)
  β”‚          -> DbContext         β”‚ ──▢ SQL Server    (real, container)
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         real objects inside

The database is outside the process but owned by you, so for data access tests it should be real; for pure logic tests above the repository, a fake is fine.

5. Measuring test quality

  • Mutation score (Stryker.NET): over-mocked suites often have high line coverage but low mutation score, because asserts check calls, not values.
  • Red-on-refactor: count tests that fail on behaviour-preserving PRs.
  • Escaped defects: bugs in wiring and mapping are the classic misses.

Try it yourself

  1. Take a handler test with five mocks; count setup lines vs assert lines.
  2. Refactor the handler (inline the mapper) and see which tests fail.
  3. Rewrite it with real validator and mapper and an in-memory fake repository; refactor again.
  4. Run Stryker.NET before and after; compare mutation scores.
  5. Introduce a bug in the real mapper and check which suite catches it.

πŸ’» Code

Before: an over-mocked handler test. After: a behaviour test with real collaborators and a fake only at the boundary.

#nullable enable
namespace Onboarding.Tests;

using NSubstitute;
using Xunit;

// Code under test
public sealed record RegisterCustomer(string Email, string Name);
public sealed record CustomerDto(Guid Id, string Email, string DisplayName);
public sealed record CustomerRegistered(Guid Id, string Email);

public interface ICustomerStore { Task AddAsync(CustomerDto c, CancellationToken ct); Task<bool> ExistsAsync(string email, CancellationToken ct); }
public interface IEventPublisher { Task PublishAsync(CustomerRegistered e, CancellationToken ct); }

public sealed class RegisterValidator
{
    public bool IsValid(RegisterCustomer c) => c.Email.Contains('@') && c.Name.Length is > 0 and <= 100;
}

public sealed class CustomerMapper
{
    public CustomerDto ToDto(RegisterCustomer c) => new(Guid.NewGuid(), c.Email.Trim().ToLowerInvariant(), c.Name.Trim());
}

public sealed class RegisterHandler(RegisterValidator validator, CustomerMapper mapper, ICustomerStore store, IEventPublisher events)
{
    public async Task<CustomerDto?> HandleAsync(RegisterCustomer cmd, CancellationToken ct)
    {
        if (!validator.IsValid(cmd) || await store.ExistsAsync(cmd.Email, ct)) return null;
        var dto = mapper.ToDto(cmd);
        await store.AddAsync(dto, ct);
        await events.PublishAsync(new(dto.Id, dto.Email), ct);
        return dto;
    }
}

// BEFORE (over-mocked, shown as a comment): validator and mapper mocked,
// asserts on internal calls. Breaks if mapping is inlined; misses mapper bugs.
//   mapper.ToDto(cmd).Returns(dto);
//   await store.Received(1).ExistsAsync("[email protected]", ct);
//   mapper.Received(1).ToDto(cmd);
//   Received.InOrder(() => { store.AddAsync(dto, ct); events.PublishAsync(...); });

// AFTER: in-memory fake for the store we own; mock only the outgoing event
file sealed class InMemoryCustomerStore : ICustomerStore
{
    public List<CustomerDto> Saved { get; } = [];
    public Task AddAsync(CustomerDto c, CancellationToken ct) { Saved.Add(c); return Task.CompletedTask; }
    public Task<bool> ExistsAsync(string email, CancellationToken ct)
        => Task.FromResult(Saved.Any(s => s.Email == email.Trim().ToLowerInvariant()));
}

public sealed class RegisterHandlerTests
{
    private readonly InMemoryCustomerStore _store = new();
    private readonly IEventPublisher _events = Substitute.For<IEventPublisher>();

    private RegisterHandler CreateSut() => new(new RegisterValidator(), new CustomerMapper(), _store, _events);

    [Fact]
    public async Task Register_NewCustomer_SavesNormalisedEmailAndPublishesEvent()
    {
        var ct = TestContext.Current.CancellationToken;

        var result = await CreateSut().HandleAsync(new(" [email protected] ", "Ana"), ct);

        // Outcome, not wiring: what was saved and what left the process
        var saved = Assert.Single(_store.Saved);
        Assert.Equal("[email protected]", saved.Email);
        Assert.Equal(saved, result);
        await _events.Received(1).PublishAsync(new CustomerRegistered(saved.Id, "[email protected]"), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Register_DuplicateEmail_IgnoringCase_IsRejected()
    {
        var ct = TestContext.Current.CancellationToken;
        await CreateSut().HandleAsync(new("[email protected]", "Ana"), ct);

        var result = await CreateSut().HandleAsync(new("[email protected]", "Ana 2"), ct);

        Assert.Null(result);
        Assert.Single(_store.Saved);
    }
}

⚠ Common mistakes

  • Mistake: Mocking every constructor dependency by default. Why it is wrong: In-process collaborators with no I/O are cheap and deterministic; mocking them hides integration bugs. Instead: Use real validators, mappers and domain services.
  • Mistake: Wiring the SUT by hand with new and mocks, instead of from the app's DI container. Why it is wrong: Tests never see real registrations, lifetimes or decorators, so a missing registration only fails at runtime. Instead: Build a ServiceCollection with the app's own AddOrders() extension (or use WebApplicationFactory) and replace only boundary services with services.Replace(...).
  • Mistake: Verifying calls to collaborators that only return data. Why it is wrong: It pins the implementation and breaks on refactor. Instead: Assert on the result those values produced.
  • Mistake: Received.InOrder as standard practice. Why it is wrong: Call order is rarely a business rule. Instead: Verify order only where it is a real requirement (e.g. save before publish, and then prefer an outbox).
  • Mistake: Updating mock setups to make red tests green after a refactor. Why it is wrong: The tests now just restate the new code; they protect nothing. Instead: Replace them with behaviour tests.
  • Mistake: Introducing an interface for every class only so it can be mocked. Why it is wrong: Interface noise with one implementation, and it encourages over-mocking. Instead: Interfaces at real boundaries; concrete classes inside.
  • Mistake: Measuring test quality by line coverage. Why it is wrong: Over-mocked suites reach high coverage while asserting little. Instead: Mutation testing with Stryker.NET.
  • Mistake: Rewriting a legacy over-mocked suite in one big bang. Why it is wrong: Big rewrites stall, compete with feature work and temporarily lose coverage. Instead: Strangle it: (1) add a few behaviour tests at the HTTP or use-case level for an area first, (2) when a refactor breaks that area's mock tests, delete them rather than repair them, (3) track the remaining mock-heavy tests as visible debt, (4) block new Received() on query methods in review.

πŸ› Senior insight: trade-offs

Over-mocking is usually a symptom of defining "unit" as "class" and of designs with an interface per class. The fix is partly in tests and partly in design: keep interfaces for genuine boundaries, keep logic in plain classes and domain objects, and test at the level where behaviour is visible. I also watch the economics: a test that has never caught a bug but breaks on every refactor has negative value, and deleting it is a legitimate improvement.

Option When it fits Cost When not to
Mock at process boundary Third-party APIs, bus, email, clock Low In-process collaborators
Fake for owned state (repo, cache) Logic tests above data access Keep fake honest Testing the query itself
Use-case level tests from real DI registrations Most application logic Less precise failure location Complex algorithms needing many cases
HTTP-level tests (WebApplicationFactory) Validation, auth, serialisation Slower, needs host setup Pure domain rules
Signal How to get it Over-mocking looks like
Setup-to-assert ratio Count lines in a sample of tests 10+ setup lines per assert
Red-on-refactor Tag behaviour-preserving PRs, count failing tests Dozens of failures, no bugs
Coverage vs mutation score Coverlet plus Stryker.NET on the same project 90% coverage, ~50% mutation score
Escaped defects by type Incident and bug tags Mapping and wiring bugs dominate

These numbers are also how I make the case to the team or a manager: they turn "our tests feel brittle" into a measurable problem with a measurable fix.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate distinguishes stubbing queries from verifying commands Why: Checks stub vs mock and state vs behaviour verification
    How to 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.

  2. When: Candidate is asked to apply this in a code review Why: Checks they can spot over-mocking and other test smells in real code
    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.

  3. When: Candidate mentions coverage or mutation score Why: Checks they know how mutation testing exposes weak asserts
    How to answer

    Code coverage tells you which lines ran during tests, not whether any test would notice if they were wrong. A test with no assertions still gives coverage. Mutation testing measures that directly: a tool makes small changes to your code, called mutants (> to >=, + to -, true to false, removing a statement), runs the tests against each, and expects at least one test to fail. A failing test kills the mutant; if all tests pass, the mutant survived, which shows a gap. Stryker.NET does this for C# via dotnet stryker and reports a mutation score with build-breaking thresholds. The trade-off is run time: it re-runs tests many times, so you scope it to core logic and use incremental --since runs.

πŸ›  Real-world problems: how you handle them

Refactor turns 140 tests red, production bug slips through anyway
Situation
A .NET 10 onboarding service with MediatR-style handlers, [about 600] unit tests, every dependency mocked via NSubstitute, [around 90%] line coverage. The team planned to merge two handlers and replace a hand-written mapper with a source-generated one.
Signals
The refactor PR turned [140] tests red with no behaviour change; developers spent [two days] updating mock setups. A week later, a renamed DTO property caused `displayName` to be null in API responses for new customers; support tickets rose and no test had failed.
Investigation
Read the failing tests: almost all asserted `Received()` on mapper, validator and repository calls. Checked the CI test report and coverage: the real mapper was never executed by any test. Ran Stryker.NET on the handlers project: mutation score [about 50%], with surviving mutants in mapping and validation.
Resolution
Hotfixed the mapping. Then replaced handler tests cluster by cluster with behaviour tests: real validator and mapper, in-memory fakes for owned stores, mocks only for the event publisher and payment API, plus endpoint tests through WebApplicationFactory with SQL Server in Testcontainers.
Prevention
Testing guideline (ADR): mock only at process boundaries; no `Received()` on query methods; Stryker.NET run weekly on core projects with a mutation-score floor; review checklist item for setup-to-assert ratio; mapper configured to fail on unmapped members.

How to tell it (STAR)

**S:** At [company], a routine refactor broke [140] unit tests without changing behaviour, and a week later a mapping bug reached production that no test caught. **T:** I was asked to make the suite trustworthy without stopping feature work. **A:** I showed the team that our tests mocked the mapper and validator everywhere, so the real chain never ran, and backed it with a Stryker.NET mutation score of [about 50%]. We agreed to mock only at process boundaries, and I replaced handler test clusters with behaviour tests as we touched each area. **R:** Over [two sprints] we went from [180] brittle tests to [45] behaviour tests in that area, the mutation score rose to [74%], and the next big refactor needed [no] test changes.

↩ Usually asked after

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me