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.
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.
"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()orVerify()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 throughWebApplicationFactory. 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 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 |
| 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) |
| 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 |
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.
Checks whether the candidate writes tests that support refactoring and catch real bugs, rather than tests that mirror the code.
Green flags
Red flags
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.
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.
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.
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.
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);
}
}
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(...).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).Received() on query methods in review.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.
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.
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.
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.
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.
Last updated 23 Nov 2026.