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

📚 Interview question

How do you mock dependencies in .NET unit tests with NSubstitute and Moq? Show how you set up return values, use argument matchers, verify calls and simulate exceptions, and tell me what happened with Moq and SponsorLink in 2023.

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.

Junior Coding Intermediate mocking moq nsubstitute supply-chain-security testing unit-testing

🎯 Key points

  • Mock interfaces or virtual members only; sealed classes and statics cannot be substituted
  • NSubstitute: Substitute.For<T>(), .Returns(...), Arg.Any<T>(), Arg.Is<T>(predicate)
  • Verification: Received(1) / DidNotReceive() in NSubstitute, Verify(..., Times.Once) in Moq
  • Exceptions and async: .Throws / .ThrowsAsync, Returns(Task.FromResult(x)) or ReturnsAsync
  • Install NSubstitute.Analyzers to catch setups on non-virtual members
  • Moq 4.20.0 (Aug 2023) bundled SponsorLink, which read the git email and sent a hash off the machine; removed in 4.20.2
  • Lesson: pin and review test dependencies like production ones

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"A mocking library uses Castle.DynamicProxy under 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, and await gateway.Received(1).ChargeAsync(...) verifies the call. For failures I use ThrowsAsync from NSubstitute.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) and Verify(..., 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."


NSubstitute and Moq side by side

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(...).

Stub or verify?

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

What the SponsorLink episode teaches

  • Test-only packages run code on developer machines and build agents, with access to source and credentials.
  • Pin versions (Central Package Management, lock files), review release notes for upgrades, and use Dependabot or Renovate with human review.
  • Under the Privacy Act 1988 an email address is personal information; tooling that sends it off-machine without notice is a governance issue, not just a technical one.

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can isolate a unit with a mocking library correctly and knows its limits and supply-chain risks.

Green flags

  • Knows only interfaces and virtual members can be mocked, and why
  • Uses argument matchers and verifies the meaningful outcome only
  • Handles async returns, exceptions and CancellationToken matching
  • Knows the SponsorLink facts and draws a supply-chain lesson

Red flags

  • Mocks DbContext or HttpClient directly
  • Verifies every call, including reads
  • Has never seen a setup silently fail to match

📚 Learn in depth

1. How a mock is generated

NSubstitute, 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.

2. How NSubstitute's syntax works

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.

3. Moq's expression trees

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.

4. Default returns

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.

5. SponsorLink timeline

  • Aug 2023, Moq 4.20.0: an analyser package was included that, at build, ran git config user.email, hashed it with SHA-256 and checked it against a CDN to show a sponsorship message.
  • Within days, community reports raised privacy, consent and GDPR concerns and broken restores on some platforms.
  • Moq 4.20.2 removed it. The maintainer later published SponsorLink separately as open source.

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).

Try it yourself

  1. Substitute an interface with a Task<T> method and call it without configuring it. Inspect what comes back.
  2. Create a class with a non-virtual method, try to stub it, and see what NSubstitute does; then install NSubstitute.Analyzers and rebuild.
  3. Write the same test with Moq and NSubstitute and compare readability.
  4. Use Arg.Do<T> to capture an argument and assert on its properties instead of using a complex Arg.Is predicate.
  5. Turn on Central Package Management and a NuGet lock file in a test project and see what changes on restore.

💻 Code

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

⚠ Common mistakes

  • Mistake: Stubbing a non-virtual method on a concrete class. Why it is wrong: The proxy cannot intercept it, so the real code runs or the setup attaches to the wrong call. Instead: Depend on an interface, and install NSubstitute.Analyzers or use Moq's strict mode to catch it.
  • Mistake: Verifying every call, including queries. Why it is wrong: Tests fail on harmless refactors and assert implementation, not behaviour. Instead: Stub queries; verify only commands that are the observable outcome.
  • Mistake: Matching a 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>().
  • Mistake: Verifying before the act has completed. Why it is wrong: In async code, checking calls before awaiting the method under test can see an incomplete picture. Instead: Await the act first, then verify.
  • Mistake: Mocking types you don't own, such as 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.
  • Mistake: Upgrading test packages without review because "it's only tests". Why it is wrong: Test packages run on developer machines and CI with access to source and secrets, as SponsorLink showed. Instead: Pin versions, review changelogs and scan dependencies like production code.
  • Mistake: Building deep recursive mocks (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.
  • Mistake: Using mocks where a fake or an integration test would be clearer. Why it is wrong: Mocks prove the unit calls its collaborators, not that the system works; stateful dependencies need many fragile setups. Instead: Unit-test logic with stubs and fakes, and cover real wiring with integration tests. Proxy generation also costs a few milliseconds per type on first use, which is negligible next to real I/O.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate uses the word mock for everything. Why: Checks vocabulary and the judgement to pick the simplest double.
    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 suggests mocking HttpClient. Why: Checks whether the candidate knows better ways to test outbound HTTP.
    How to answer

    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.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me