Lesson 45 of 93 · 5 min read · Updated
NSubstitute vs Moq: The Same Unit Test Written with Both Libraries
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- NSubstitute 6.2.0 (BSD-3-Clause licence)
- FluentAssertions 7.2.2
- 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
The Same Scenario in NSubstitute
M05.TestableDesign.Tests/NSubstituteComparisonTests.cs
Three differences stand out:
Substitute.For<T>()returns aTdirectly. The service receivesgateway, notgateway.Object.- Configuration is a normal method call followed by
.Returns(...). For a method returningTask<T>, NSubstitute wraps the value in a completed task, so there is no separateReturnsAsync. - Verification reads like the call it checks:
gateway.Received(1).CaptureAsync(...). Theawaitis 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
| Task | Moq | NSubstitute |
|---|---|---|
| Create | new Mock<T>(), then mock.Object | Substitute.For<T>() |
| Return a value | Setup(x => x.M(...)).ReturnsAsync(v) | sub.M(...).Returns(v) |
| Any argument | It.IsAny<T>() | Arg.Any<T>() |
| Conditional argument | It.Is<T>(x => ...) | Arg.Is<T>(x => ...) |
| Throw | .ThrowsAsync(ex) | .ThrowsAsync(ex) with using NSubstitute.ExceptionExtensions; |
| Verify count | Verify(..., Times.Once) | await sub.Received(1).M(...) |
| Verify not called | Verify(..., Times.Never) | await sub.DidNotReceive().M(...) |
The decline path shows DidNotReceive, and the error path shows ThrowsAsync:
M05.TestableDesign.Tests/NSubstituteComparisonTests.cs
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
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
- NSubstitute's
Substitute.For<T>()returns the interface directly; there is no.Object. - Configure with
sub.Method(...).Returns(value); tasks are wrapped automatically. - Verify with
Received(n)andDidNotReceive();ThrowsAsyncneedsNSubstitute.ExceptionExtensions. - Do not mix
Arg.Anywith plain or defaulted arguments in one call; passArg.Any<CancellationToken>()explicitly. - Choosing between Moq, NSubstitute and a hand-written double is a matter of style; what you verify matters more.