skip to content

In .NET 10 unit tests, how do Moq 4.21, NSubstitute 6 and FakeItEasy 9 differ in stubbing a call, checking it happened and answering unconfigured calls?

level: middleimportance: should knowfreq 45%

answer

  1. wrapper object versus the fake itself
  2. Setup / Returns / Verify
  3. Returns / Received(1)
  4. A.CallTo(...).MustHaveHappenedOnceExactly()
  5. defaults, auto-values, dummies

basics

~10 s

Moq wraps the type: mock.Setup(...).Returns(...) and mock.Verify(..., Times.Once()). NSubstitute calls the substitute itself: sub.Find(...).Returns(...) and sub.Received(1).Find(...). FakeItEasy uses A.CallTo(() => fake.Find(...)).Returns(...) and MustHaveHappenedOnceExactly().

solid answer

~40 s

All three generate runtime proxies for interfaces and overridable members, so they solve the same problem with different grammar. **Moq** keeps configuration on a `Mock<T>` wrapper and injects `mock.Object`; matchers are `It.IsAny<T>()` and `It.Is<T>(...)`; failures throw `MockException`. **NSubstitute** returns the fake itself from `Substitute.For<T>()`, so you call the member and chain `.Returns(...)`; checks read `sub.Received(1).Member(...)` with `Arg.Any<T>()`, failing with `ReceivedCallsException`. **FakeItEasy** creates `A.Fake<T>()` and configures through `A.CallTo(() => fake.Member(...))`, with `A<T>._` as the wildcard and `ExpectationException` on failure. Unconfigured calls differ: Moq's loose default returns `null`, zero, empty collections and completed tasks; NSubstitute returns `""` for strings, empty arrays, completed tasks and recursive substitutes for interfaces; FakeItEasy returns a Dummy, such as `""` or another fake, falling back to `default`. Moq 4.20.0 briefly bundled SponsorLink, which 4.20.2 removed.

code

csharp · 11 lines
csharp
// NSubstitute 6
var coupons = Substitute.For<ICouponRepository>();
coupons.FindAsync("SPRING10", Arg.Any<CancellationToken>())
       .Returns(new Coupon("SPRING10", Percent: 10));
var events = Substitute.For<IDomainEvents>();

await new ApplyDiscountHandler(coupons, events)
    .HandleAsync(50m, "SPRING10", CancellationToken.None);

await events.Received(1).PublishAsync(
    Arg.Is<DiscountApplied>(d => d.Percent == 10), Arg.Any<CancellationToken>());

go deeper

for a junior

Recognise each library's create, stub and verify calls so you can read a test written with any of them.

for a middle

Explain what each returns for an unconfigured call, how their exactly-once checks are spelled, and which exception each throws on failure.

for a senior

Spot tests that pass because of auto-values or loose defaults, and know the matcher-placement traps that make setups silently not match.

for a principal

Choose one library per solution on readability, licence and supply-chain grounds, and plan how to migrate if that choice has to change.

## Same job, three grammars Moq, NSubstitute and FakeItEasy all create **runtime proxies**: generated classes that implement an interface, or override the virtual and abstract members of a class, and record every call. None of them can intercept non-virtual members, static members or extension methods. The differences are in how a test talks to the proxy and in what the proxy does when nobody configured it. ## The grocery example in each library The discount handler depends on `ICouponRepository.FindAsync(code, ct)` and `IDomainEvents.PublishAsync(evt, ct)`. | Step | Moq 4.21 | NSubstitute 6 | FakeItEasy 9 | |---|---|---|---| | create | `new Mock<ICouponRepository>()` | `Substitute.For<ICouponRepository>()` | `A.Fake<ICouponRepository>()` | | object to inject | `mock.Object` | the substitute itself | the fake itself | | any-value matcher | `It.IsAny<T>()` | `Arg.Any<T>()` | `A<T>._` (or `A<T>.Ignored`) | | predicate matcher | `It.Is<T>(x => ...)` | `Arg.Is<T>(x => ...)` | `A<T>.That.Matches(x => ...)` | | stub an async result | `.Setup(...).ReturnsAsync(c)` | `.FindAsync(...).Returns(c)` | `A.CallTo(() => ...).Returns(c)` | | exactly once | `Verify(..., Times.Once())` | `Received(1).PublishAsync(...)` | `.MustHaveHappenedOnceExactly()` | | never | `Times.Never()` | `DidNotReceive()` | `.MustNotHaveHappened()` | | failure type | `MockException` | `ReceivedCallsException` | `ExpectationException` | NSubstitute and FakeItEasy both accept a plain value for a `Task<T>` member and wrap it in a completed task; Moq spells that `ReturnsAsync`. ## Unconfigured calls This is where the libraries really differ, and it decides how a test fails when a setup is missing: - **Moq** (`MockBehavior.Loose`, the default) returns `null` for reference types, `0` or `false` for value types, empty arrays, enumerables and queryables, and completed tasks holding defaults. `MockBehavior.Strict` throws `MockException` instead. - **NSubstitute** returns **auto-values**: `string.Empty` for strings, empty arrays, completed tasks, and, for interfaces, delegates and purely virtual classes, a new **recursive substitute**. `sub.Customer.Address.City` therefore works without setup, which is convenient and occasionally hides a missing stub. - **FakeItEasy** returns a **Dummy** when it can make one: `string.Empty`, a completed task, another fake for a fakeable type; otherwise `default(T)`. `A.Fake<T>(o => o.Strict())` makes unconfigured calls throw. A missing setup in Moq tends to surface as a `NullReferenceException` deep in the handler; in NSubstitute or FakeItEasy it more often surfaces as an empty string or a fake object flowing on, which can make a wrong test pass. Assert on outcomes, not just on the absence of exceptions. ## Traps specific to each 1. **Moq**: `It.IsAny<T>()` passed into a string-based `Protected()` setup is evaluated before Moq sees it, becomes a `default` constant and matches only null. Use `ItExpr` there. 2. **NSubstitute**: argument matchers such as `Arg.Any<T>()` must appear inside the call being configured or checked; stray matchers make NSubstitute throw `AmbiguousArgumentsException` or `RedundantArgumentMatcherException`. `Received()` without a count means at least once; use `Received(1)` for exactly once. 3. **FakeItEasy**: the `A.CallTo` lambda must call a member of a fake; pointing it at a real object fails, and configuring a non-virtual member is rejected. ## Partial fakes of classes Sometimes the type is a class whose real behaviour you want except for one virtual member: | Library | Partial fake | Effect | |---|---|---| | Moq | `new Mock<T> { CallBase = true }` | unconfigured virtual members run the base implementation | | NSubstitute | `Substitute.ForPartsOf<T>()` | real implementation unless a member is configured | | FakeItEasy | `A.CallTo(...).CallsBaseMethod()` | the configured call runs the base implementation | Partial fakes are a smell in new code, because they test a class against a modified copy of itself, but they help when wrapping legacy types that have no interface. ## Picking one in a .NET 10 codebase - All three run on .NET 10 test projects; NSubstitute 6 targets .NET 8 and .NET Standard 2.0. - The choice is mostly about readability. Moq's wrapper keeps configuration visibly separate; NSubstitute reads like the production call; FakeItEasy reads like a sentence. - Licence and supply-chain history can matter to a team. Moq is BSD-3-Clause. Its changelog records that 4.20.0 added SponsorLink, that users raised privacy issues with it, and that 4.20.2 removed it; later entries record it as no longer bundled. Some teams moved libraries during that episode, which is why interviewers sometimes ask about it. - Mixing libraries inside one test project makes every test harder to read; pick one per solution.

  • A NSubstitute test passes even though the repository stub was never configured. How can that happen?
    Unconfigured members return auto-values: an empty string, a completed task or a recursive substitute for interface types. If the handler only checks for null, an auto-substituted object flows through as if it were real data. Configure the member explicitly and assert on the handler's actual output.
  • How do you make a FakeItEasy fake fail on any call you did not configure?
    Create it with `A.Fake<ICouponRepository>(o => o.Strict())`. Every call without a matching `A.CallTo` configuration then throws, which is the equivalent of Moq's `MockBehavior.Strict`.

  • NSubstitute's Received() with no count asserts exactly one call.
  • Every mocking library returns null for any call you did not configure.
  • FakeItEasy and NSubstitute can intercept non-virtual class methods, unlike Moq.
  • NSubstitute's Arg.Any<T>() can be stored in a variable and reused later.
  • Moq still ships SponsorLink in every 4.20 and later release.

Assumes Moq 4.21, NSubstitute 6.2 and FakeItEasy 9.0 in ASP.NET Core 10 test projects; Moq 4.20.0 bundled SponsorLink and 4.20.2 removed it.