Lesson 45 of 93 · 5 min read · Updated

NSubstitute vs Moq: The Same Unit Test Written with Both Libraries

Moq is not the only mocking library for .NET. NSubstitute offers the same features with less ceremony: there is no Mock<T> wrapper, no .Object and no lambda around every call. This lesson writes the same checkout scenario with Moq and with NSubstitute, side by side, maps the APIs to each other, and points out the one NSubstitute trap that catches most newcomers. It ends with a reminder that a hand-written double is often enough.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Moq 4.21.0
  4. NSubstitute 6.2.0 (BSD-3-Clause licence)
  5. FluentAssertions 7.2.2
  6. Microsoft.Extensions.TimeProvider.Testing 11.0.0

The Scenario in Moq

A valid 10 percent coupon is applied to a 1000 TRY checkout. The test checks the charged amount and that the discounted amount is captured exactly once.

M05.TestableDesign.Tests/NSubstituteComparisonTests.cs

[Fact]
public async Task Moq_PayAsync_WithValidCoupon_CapturesDiscountedAmountOnce()
{
// Arrange
var gateway = new Mock<IPaymentGateway>();
var coupons = new Mock<ICouponRepository>();

coupons
.Setup(x => x.FindAsync("BAHAR10", It.IsAny<CancellationToken>()))
.ReturnsAsync(Coupons.TenPercentValid());
gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Approve("AUTH-MOQ"));

var sut = new CheckoutService(
gateway.Object, coupons.Object, new FakeTimeProvider(Now), NullLogger<CheckoutService>.Instance);

// Act
var result = await sut.PayAsync(Money.Try(1_000m), "BAHAR10");

// Assert
result.Charged.Should().Be(Money.Try(900m));
gateway.Verify(
x => x.CaptureAsync("AUTH-MOQ", It.Is<Money>(m => m.Amount == 900m), It.IsAny<CancellationToken>()),
Times.Once);
}

The Same Scenario in NSubstitute

M05.TestableDesign.Tests/NSubstituteComparisonTests.cs

[Fact]
public async Task NSubstitute_PayAsync_WithValidCoupon_CapturesDiscountedAmountOnce()
{
// Arrange - no .Object: the substitute IS the object itself.
var gateway = Substitute.For<IPaymentGateway>();
var coupons = Substitute.For<ICouponRepository>();

coupons.FindAsync("BAHAR10", Arg.Any<CancellationToken>())
.Returns(Coupons.TenPercentValid());
gateway.AuthorizeAsync(Arg.Any<Money>(), Arg.Any<CancellationToken>())
.Returns(Authorization.Approve("AUTH-NSUB"));

var sut = new CheckoutService(
gateway, coupons, new FakeTimeProvider(Now), NullLogger<CheckoutService>.Instance);

// Act
var result = await sut.PayAsync(Money.Try(1_000m), "BAHAR10");

// Assert - Received(1): "called exactly once".
result.Charged.Should().Be(Money.Try(900m));
await gateway.Received(1).CaptureAsync(
"AUTH-NSUB",
Arg.Is<Money>(m => m.Amount == 900m),
Arg.Any<CancellationToken>());
}

Three differences stand out:

  1. Substitute.For<T>() returns a T directly. The service receives gateway, not gateway.Object.
  2. Configuration is a normal method call followed by .Returns(...). For a method returning Task<T>, NSubstitute wraps the value in a completed task, so there is no separate ReturnsAsync.
  3. Verification reads like the call it checks: gateway.Received(1).CaptureAsync(...). The await is not required for correctness, but it keeps the compiler from warning about an unawaited task.

Which one to pick is a team decision. Moq's explicit Setup and Verify make the difference between configuring and checking visible. NSubstitute reads more like ordinary code. Both are free, open-source libraries. Pick one per codebase and use it consistently, so readers do not have to switch styles between files.

API Map

TaskMoqNSubstitute
Createnew Mock<T>(), then mock.ObjectSubstitute.For<T>()
Return a valueSetup(x => x.M(...)).ReturnsAsync(v)sub.M(...).Returns(v)
Any argumentIt.IsAny<T>()Arg.Any<T>()
Conditional argumentIt.Is<T>(x => ...)Arg.Is<T>(x => ...)
Throw.ThrowsAsync(ex).ThrowsAsync(ex) with using NSubstitute.ExceptionExtensions;
Verify countVerify(..., Times.Once)await sub.Received(1).M(...)
Verify not calledVerify(..., Times.Never)await sub.DidNotReceive().M(...)

The decline path shows DidNotReceive, and the error path shows ThrowsAsync:

M05.TestableDesign.Tests/NSubstituteComparisonTests.cs

[Fact]
public async Task NSubstitute_PayAsync_WhenDeclined_DoesNotCapture()
{
// Arrange
var gateway = Substitute.For<IPaymentGateway>();
gateway.AuthorizeAsync(Arg.Any<Money>(), Arg.Any<CancellationToken>())
.Returns(Authorization.Decline("Yetersiz bakiye"));

var sut = new CheckoutService(
gateway, Substitute.For<ICouponRepository>(), new FakeTimeProvider(Now),
NullLogger<CheckoutService>.Instance);

// Act
var result = await sut.PayAsync(Money.Try(1_000m), couponCode: null);

// Assert - DidNotReceive: no money must have been captured.
result.Failure.Should().Be("Yetersiz bakiye");
await gateway.DidNotReceive().CaptureAsync(
Arg.Any<string>(), Arg.Any<Money>(), Arg.Any<CancellationToken>());
}

[Fact]
public async Task NSubstitute_PayAsync_WhenGatewayIsDown_PropagatesException()
{
// Arrange - ThrowsAsync comes from NSubstitute.ExceptionExtensions.
var gateway = Substitute.For<IPaymentGateway>();
gateway.AuthorizeAsync(Arg.Any<Money>(), Arg.Any<CancellationToken>())
.ThrowsAsync(new HttpRequestException("Ağ geçidi yanıt vermiyor"));

var sut = new CheckoutService(
gateway, Substitute.For<ICouponRepository>(), new FakeTimeProvider(Now),
NullLogger<CheckoutService>.Instance);

// Act
var act = () => sut.PayAsync(Money.Try(1_000m), couponCode: null);

// Assert
await act.Should().ThrowAsync<HttpRequestException>()
.WithMessage("*yanıt vermiyor*");
}

An unconfigured NSubstitute call returns an automatic value. For Task<Coupon?> that is a completed task whose result is null, never a null task, so the service treats the coupon as "not found".

Pitfall: Mixing Matchers and Plain Values

NSubstitute records argument matchers such as Arg.Any<T>() on a hidden queue and matches them to parameters by position. If a call mixes matchers and plain values in a way NSubstitute cannot line up, for example when several parameters share a type, it throws AmbiguousArgumentsException. Optional parameters make this easy to hit: if you write gateway.AuthorizeAsync(Arg.Any<Money>()) and let the CancellationToken default, the matcher queue and the parameter list may no longer line up. Even when no exception is thrown, the setup then matches only the default token, so a call that passes a real token is not matched. Rule of thumb: in a setup or Received call, either use plain values for all arguments or give every argument, including the optional CancellationToken, an explicit value or Arg.Any<T>().

A Hand-Written Double Is Often Enough

Neither library is required. For a narrow interface, a small class can record what happened.

M05.TestableDesign.Tests/NSubstituteComparisonTests.cs

private sealed class HandwrittenGateway : IPaymentGateway
{
public List<(string Reference, Money Amount)> Captures { get; } = [];

public Task<Authorization> AuthorizeAsync(Money amount, CancellationToken cancellationToken = default) =>
Task.FromResult(Authorization.Approve("AUTH-EL"));

public Task CaptureAsync(string reference, Money amount, CancellationToken cancellationToken = default)
{
Captures.Add((reference, amount));
return Task.CompletedTask;
}
}

A test can then assert gateway.Captures.Should().ContainSingle(). The difference between Moq, NSubstitute and a hand-written fake is mostly syntax. The real skill is deciding what to fake and what to verify.

A hand-written double has two advantages. It needs no library and no knowledge of matcher rules, and its behavior is plain C# that any reader understands. Its cost is maintenance: every new interface method must be implemented, even if no test uses it. That trade-off favors hand-written doubles for small, stable interfaces and libraries for wide or changing ones.

Summary

  1. NSubstitute's Substitute.For<T>() returns the interface directly; there is no .Object.
  2. Configure with sub.Method(...).Returns(value); tasks are wrapped automatically.
  3. Verify with Received(n) and DidNotReceive(); ThrowsAsync needs NSubstitute.ExceptionExtensions.
  4. Do not mix Arg.Any with plain or defaulted arguments in one call; pass Arg.Any<CancellationToken>() explicitly.
  5. Choosing between Moq, NSubstitute and a hand-written double is a matter of style; what you verify matters more.