Covers creating substitutes with NSubstitute and Moq, configuring returns, argument matchers, verifying received calls, throwing exceptions, async members, analysers, and the 2023 Moq SponsorLink supply-chain controversy.
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.
"A mocking library uses
Castle.DynamicProxyunder the hood to generate a class at runtime that implements an interface or overrides virtual members. That means I can only substitute interfaces, abstract classes or virtual methods: not sealed classes, not static methods, not extension methods. In a unit test I use it for dependencies that are slow or non-deterministic, like a payment gateway or an email sender, so I can control what they return and check what my code sent them.These days I reach for NSubstitute first because the syntax reads like normal code.
Substitute.For<IPaymentGateway>()creates it,gateway.ChargeAsync(Arg.Any<decimal>(), Arg.Any<CancellationToken>()).Returns(result)stubs it,Arg.Is<T>(predicate)matches specific arguments, andawait gateway.Received(1).ChargeAsync(...)verifies the call. For failures I useThrowsAsyncfromNSubstitute.ExceptionExtensions. I always add NSubstitute.Analyzers, because setting up a non-virtual member silently does nothing and the analyser turns that into a build error. Moq does the same things with lambdas:Setup(x => x.ChargeAsync(It.IsAny<decimal>(), It.IsAny<CancellationToken>())).ReturnsAsync(result)andVerify(..., Times.Once).On SponsorLink: in August 2023 Moq 4.20.0 shipped an analyser that, during build, read the developer's git email from config, hashed it and checked it against an online sponsor list. Nobody had opted in, the hash was sent off the machine, and it broke some restores, so there was a strong backlash about privacy and trust, and it was removed in 4.20.2 days later. Plenty of teams moved to NSubstitute then. The mistake I see is not the library choice, it's verifying every call: mock the boundary, stub queries, and only verify commands that are the actual outcome."
| Task | NSubstitute | Moq |
|---|---|---|
| Create | Substitute.For<IRepo>() |
new Mock<IRepo>() then .Object |
| Stub return | repo.Get(1).Returns(x) |
mock.Setup(r => r.Get(1)).Returns(x) |
| Any argument | Arg.Any<int>() |
It.IsAny<int>() |
| Predicate | Arg.Is<int>(i => i > 0) |
It.Is<int>(i => i > 0) |
| Async return | .Returns(Task.FromResult(x)) |
.ReturnsAsync(x) |
| Throw | .Throws(ex) / .ThrowsAsync(ex) |
.Throws(ex) / .ThrowsAsync(ex) |
| Verify | Received(1), DidNotReceive() |
Verify(..., Times.Once), Times.Never |
| Capture argument | Arg.Do<T>(x => captured = x) |
Callback<T>(x => captured = x) |
| Strict mode | Not built in | MockBehavior.Strict |
| Licence | BSD-3-Clause | BSD-3-Clause |
FakeItEasy (MIT) is a third option with A.Fake<T>() and A.CallTo(...).
| Dependency call | What to do |
|---|---|
| Query (returns data, no side effect) | Stub the return; don't verify it |
| Command that is the outcome (charge card, send email, publish event) | Verify it, with the important arguments |
| Logging, metrics | Usually neither; use FakeLogger if the log is the requirement |
A checkout service had 600 tests using Moq with Verify on every repository read. A refactor that merged two reads into one query broke 140 tests without changing behaviour. Moving to NSubstitute with stubs for queries and Received only for the payment and event-publish calls cut the breakage on the next refactor to 6 tests, all real behaviour changes.
Checks that the candidate can isolate a unit with a mocking library correctly and knows its limits and supply-chain risks.
Green flags
CancellationToken matchingRed flags
DbContext or HttpClient directlyNSubstitute, Moq and FakeItEasy all build on Castle DynamicProxy, which emits a new type at runtime with System.Reflection.Emit:
IPaymentGateway (interface)
^
| implements
Castle.Proxies.IPaymentGatewayProxy (emitted at runtime)
|
interceptor --> recorded calls + configured returns
Every call goes to an interceptor. The library records the call (for later verification) and looks up a configured return. This is why only interfaces and virtual members work: a non-virtual method on a class cannot be overridden, so the proxy never sees the call.
repo.Get(1).Returns(x) looks like it calls Get, and it does. NSubstitute records that call as the "last call", and Returns attaches the value to it. Arg.Any<int>() pushes an argument specification onto a thread-local queue that the next call consumes. That clever trick has a failure mode: if Get is non-virtual, the real method runs, no call is recorded, and Returns throws CouldNotSetReturnDueToNoLastCallException or, worse, attaches to a different call. NSubstitute.Analyzers catches this at compile time.
Moq takes Expression<Func<T, TResult>> in Setup and Verify, parses the expression tree to find the method and argument matchers (It.IsAny<T>()), and stores a setup. It is more verbose but explicit, and MockBehavior.Strict throws for any call you did not set up.
An unconfigured NSubstitute member returns a sensible default: null or default value, empty for arrays, a completed Task for Task, and an auto-substitute for interface return types ("recursive mocks"). Moq's default MockBehavior.Loose returns default. Knowing this explains tests that pass because a dependency quietly returned null.
git config user.email, hashed it with SHA-256 and checked it against a CDN to show a sponsorship message.The event pushed many organisations to treat test dependencies under the same supply-chain controls as production ones (ACSC Essential Eight "application control" and "patch applications" thinking applies to build agents too).
Task<T> method and call it without configuring it. Inspect what comes back.Arg.Do<T> to capture an argument and assert on its properties instead of using a complex Arg.Is predicate.A checkout service and its unit tests with NSubstitute, plus the same verification in Moq:
// CheckoutService.cs (code under test)
namespace Shop.Checkout;
public sealed record Order(int Id, decimal Total, string Status);
public sealed record ChargeResult(bool Succeeded, string? Reference);
public interface IOrderRepository
{
Task<Order?> GetAsync(int id, CancellationToken ct);
Task SaveAsync(Order order, CancellationToken ct);
}
public interface IPaymentGateway
{
Task<ChargeResult> ChargeAsync(decimal amount, CancellationToken ct);
}
public sealed class CheckoutService(IOrderRepository orders, IPaymentGateway payments)
{
public async Task<bool> PayAsync(int orderId, CancellationToken ct)
{
var order = await orders.GetAsync(orderId, ct)
?? throw new InvalidOperationException($"Order {orderId} not found");
var result = await payments.ChargeAsync(order.Total, ct);
if (!result.Succeeded) return false;
await orders.SaveAsync(order with { Status = "Paid" }, ct);
return true;
}
}
// CheckoutServiceTests.cs (xunit.v3 + NSubstitute)
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Shop.Checkout;
using Xunit;
namespace Shop.Checkout.Tests;
public sealed class CheckoutServiceTests
{
private readonly IOrderRepository _orders = Substitute.For<IOrderRepository>();
private readonly IPaymentGateway _payments = Substitute.For<IPaymentGateway>();
private readonly CheckoutService _sut;
public CheckoutServiceTests()
{
_sut = new CheckoutService(_orders, _payments);
// Stub the query; we won't verify it.
_orders.GetAsync(42, Arg.Any<CancellationToken>())
.Returns(Task.FromResult<Order?>(new Order(42, 99.95m, "New")));
}
[Fact]
public async Task Successful_charge_saves_order_as_paid()
{
_payments.ChargeAsync(99.95m, Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new ChargeResult(true, "ch_123")));
var paid = await _sut.PayAsync(42, TestContext.Current.CancellationToken);
Assert.True(paid);
// Verify the command that is the outcome, with the argument that matters.
await _orders.Received(1).SaveAsync(
Arg.Is<Order>(o => o.Id == 42 && o.Status == "Paid"), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Declined_charge_does_not_save()
{
_payments.ChargeAsync(Arg.Any<decimal>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new ChargeResult(false, null)));
Assert.False(await _sut.PayAsync(42, TestContext.Current.CancellationToken));
await _orders.DidNotReceive().SaveAsync(Arg.Any<Order>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Gateway_timeout_propagates()
{
_payments.ChargeAsync(Arg.Any<decimal>(), Arg.Any<CancellationToken>())
.ThrowsAsync(new TimeoutException());
await Assert.ThrowsAsync<TimeoutException>(
() => _sut.PayAsync(42, TestContext.Current.CancellationToken));
}
}
// The same success test in Moq, for comparison.
var orders = new Mock<IOrderRepository>();
orders.Setup(o => o.GetAsync(42, It.IsAny<CancellationToken>())).ReturnsAsync(new Order(42, 99.95m, "New"));
var payments = new Mock<IPaymentGateway>();
payments.Setup(p => p.ChargeAsync(99.95m, It.IsAny<CancellationToken>())).ReturnsAsync(new ChargeResult(true, "ch_123"));
var sut = new CheckoutService(orders.Object, payments.Object);
await sut.PayAsync(42, CancellationToken.None);
orders.Verify(o => o.SaveAsync(It.Is<Order>(x => x.Status == "Paid"), It.IsAny<CancellationToken>()), Times.Once);
CancellationToken with a specific value like CancellationToken.None. Why it is wrong: The code passes a different token, so the setup never matches and returns default. Instead: Use Arg.Any<CancellationToken>() / It.IsAny<CancellationToken>().HttpClient or DbContext. Why it is wrong: Their real behaviour (handlers, change tracking, SQL translation) is complex, so a mock simulates it inadequately and tests pass while production fails. Instead: Use WireMock.Net or a stub HttpMessageHandler for HTTP and a real database (Testcontainers) for EF Core.a.B.C.D.Returns(x)). Why it is wrong: It signals Law of Demeter violations and makes tests brittle. Instead: Fix the design so the unit takes what it needs directly.The library matters far less than what you mock. Mock at the boundaries you own (ports such as IPaymentGateway, IClock, IEmailSender), use real implementations or fakes for everything in-process, and use real infrastructure in integration tests. If a test needs more than three or four substitutes, the class under test probably has too many responsibilities.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| NSubstitute | Default for new code; readable, forgiving | Needs analyser to catch non-virtual setups | When you want strict "fail on any unexpected call" |
| Moq | Existing suites, teams that like strict mode | Verbose lambdas; trust hit after SponsorLink | New projects with no reason to prefer it |
| FakeItEasy | Teams that like A.CallTo syntax |
Smaller community | Mixed in with another library in the same suite |
| Hand-written fake | Stateful dependencies (in-memory repository, fake clock) | A small class to maintain | One-off stubs a library does in one line |
Measure the cost of over-mocking by counting how many tests fail on a pure refactor; that number should be close to zero.
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.
Point the typed HttpClient at a WireMock.Net server in the test and configure it to return 500s, 429s with Retry-After, or delayed responses. Then assert your API's behaviour: the resilience pipeline (AddStandardResilienceHandler) retries the right number of times, the timeout fires, the circuit breaker opens, and the endpoint returns a sensible ProblemDetails (502 or 503) instead of hanging. Use FakeTimeProvider where possible so retries and timeouts don't make the test slow, and check WireMock's request log to count retries.
Last updated 23 Nov 2026.