skip to content

Unit Tests & Fakes

Unit tests call handlers, filters and middleware directly with a DefaultHttpContext and doubles from Moq, NSubstitute or FakeItEasy. Interviewers test what you mock and what you leave real.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

With Moq 4.21, how do you stub a coupon repository and verify an event was published when unit testing a grocery app's discount handler?

level: juniorimportance: must knowfreq 72%

answer

  1. Mock<T> plus .Object
  2. Setup(...).ReturnsAsync(value)
  3. It.IsAny<T>() and It.Is<T>(predicate)
  4. Verify(..., Times.Once())
  5. Loose by default; Strict throws MockException

basics

~20 s

Create a Mock<ICouponRepository>, Setup the lookup with It.IsAny<CancellationToken>() and ReturnsAsync(coupon), pass mock.Object to the handler, then call Verify on the event publisher's mock with Times.Once(). Calls you never set up return defaults rather than failing.

solid answer

~40 s

`new Mock<ICouponRepository>()` builds a runtime proxy whose behaviour is `MockBehavior.Loose` by default. `Setup(r => r.FindAsync("SPRING10", It.IsAny<CancellationToken>())).ReturnsAsync(coupon)` stubs the lookup: literal arguments match by equality, `It.IsAny<T>()` matches anything and `It.Is<T>(predicate)` matches what the lambda accepts. Inject `coupons.Object` and `events.Object` into the handler, act, then assert the interaction with `events.Verify(e => e.PublishAsync(It.Is<DiscountApplied>(d => d.Percent == 10), It.IsAny<CancellationToken>()), Times.Once())`, which throws `MockException` listing the calls actually received. A loose mock answers unconfigured calls with defaults: `null`, `0`, empty arrays and enumerables, and completed tasks. `MockBehavior.Strict` throws instead. Moq can only intercept interface members and overridable class members; setting up a non-virtual or extension method such as `ILogger.LogWarning` throws `NotSupportedException`.

code

csharp · 23 lines
csharp
using Moq;
using Xunit;

public class ApplyDiscountHandlerTests
{
    [Fact]
    public async Task Valid_coupon_reduces_total_and_publishes_event()
    {
        var coupons = new Mock<ICouponRepository>();
        coupons.Setup(r => r.FindAsync("SPRING10", It.IsAny<CancellationToken>()))
               .ReturnsAsync(new Coupon("SPRING10", Percent: 10));
        var events = new Mock<IDomainEvents>();

        var handler = new ApplyDiscountHandler(coupons.Object, events.Object);
        var total = await handler.HandleAsync(50m, "SPRING10", CancellationToken.None);

        Assert.Equal(45m, total);
        events.Verify(e => e.PublishAsync(
                It.Is<DiscountApplied>(d => d.Code == "SPRING10" && d.Percent == 10),
                It.IsAny<CancellationToken>()),
            Times.Once());
    }
}

go deeper

for a junior

Recall Mock<T>, Setup with Returns or ReturnsAsync, .Object for injection, It.IsAny<T>() and Verify with Times.Once().

for a middle

Explain loose versus strict behaviour, which default values an unconfigured call returns, how matchers choose a setup, and why only overridable members can be mocked.

for a senior

Keep verification for interactions that are the behaviour, prefer asserting on results, and know which framework seams need purpose-built fakes instead of Moq.

for a principal

Set team conventions on mocking style and strictness so tests stay readable and do not freeze implementation details into hundreds of verifications.

## The scenario The grocery app's `ApplyDiscountHandler` takes a basket total and a coupon code. It asks `ICouponRepository.FindAsync(code, ct)` for the coupon, applies the percentage and publishes a `DiscountApplied` event through `IDomainEvents.PublishAsync(evt, ct)`. A unit test wants two things: control what the repository returns, and prove the event went out once with the right content. Moq covers both with one type, `Mock<T>`. ## Arrange: creating and configuring the mock 1. **Create** `var coupons = new Mock<ICouponRepository>();`. Moq generates a proxy class at runtime that implements the interface. 2. **Stub** with `Setup(expression)`. The lambda is an expression tree that Moq inspects rather than runs, which is how it knows which member and which argument matchers you mean. 3. **Return** with `Returns(value)`, or for `Task<T>` and `ValueTask<T>` members the shortcut `ReturnsAsync(value)`. `Throws(...)` and `ThrowsAsync(...)` simulate failures; `Callback(...)` runs code when the call happens. 4. **Inject** `coupons.Object`, the proxy instance, into the code under test. ## Argument matchers | Written in the setup | Matches | |---|---| | a literal such as `"SPRING10"` | an argument equal to that value | | `It.IsAny<CancellationToken>()` | any value of that type, including `default` | | `It.Is<DiscountApplied>(d => d.Percent == 10)` | values the predicate accepts | | `It.IsInRange(1, 5, Range.Inclusive)` | values inside the range | When several setups match the same call, the most recently added one wins, so a general setup followed by a specific one behaves as expected. ## Loose versus Strict `MockBehavior.Default` equals `Loose`. A loose mock never throws for an unconfigured call. It returns `null` for reference types, `0` or `false` for value types, empty arrays, enumerables and queryables, and for `Task`, `Task<T>` and `ValueTask<T>` a completed task holding the default value. That last point matters for async code: the handler can `await events.PublishAsync(...)` without any setup. With `new Mock<T>(MockBehavior.Strict)` every call without a setup throws `MockException`. That catches unexpected interactions, but it also makes each test enumerate every call, so strict mocks are usually kept for the few places where an unexpected call is the bug. ## Verifying the interaction `Verify(expression, Times.Once())` checks the calls the proxy recorded: - `Times.Once()` means exactly one, `Times.Never()` none, `Times.Exactly(n)` exactly n, `Times.AtLeastOnce()` one or more. - On failure Moq throws `MockException` whose message lists the expected call and every invocation it actually saw, which usually explains the bug. - `VerifyNoOtherCalls()` fails if the mock received calls that no `Verify` has covered. - The parameterless `mock.Verify()` checks only setups marked `.Verifiable()`; `VerifyAll()` checks every setup. ## Async and multi-call specifics Handlers in ASP.NET Core are asynchronous, and Moq has helpers for each shape: - `ReturnsAsync(value)` for `Task<T>` and `ValueTask<T>` members; it is shorthand for `Returns(Task.FromResult(value))`. - `ThrowsAsync(exception)` returns a faulted task, which is what an awaiting caller really sees, rather than throwing synchronously from the call. - `SetupSequence(...)` returns different results on successive calls, for example a first lookup that times out and a second that succeeds. - `Callback(...)` or `Capture.In(list)` records the arguments so the test can assert on them afterwards, which is often clearer than a long `It.Is` predicate inside `Verify`. ## What Moq cannot intercept Moq builds subclasses or interface implementations, so it can only intercept members a subclass could override: - **Interface members** and **virtual or abstract** class members work. - **Non-virtual members**, such as `HttpClient.GetAsync`, throw `NotSupportedException` with a message naming non-overridable members. - **Extension methods**, such as `LoggerExtensions.LogWarning`, throw `NotSupportedException` because they are static methods compiled into the caller; the call that reaches the mock is the underlying interface method. - **Sealed classes** and **static members** cannot be mocked at all. The practical rule for ASP.NET Core code is to depend on interfaces or abstract types you own, and to use the purpose-built fakes for framework seams: a stub `HttpMessageHandler` for `HttpClient`, `FakeLogger<T>` for logging and `FakeTimeProvider` for time. ## Mistakes interviewers listen for - Using `CancellationToken.None` as the setup argument when the handler passes a real token; the setup never matches and the loose mock quietly returns `null`. - Treating `Times.Once()` as at least once. - Asserting on the mock's setup instead of on the handler's result, so the test proves only that the mock returns what it was told. - Calling `mock.Verify()` with no arguments and believing it checked every call.

  • When would you choose MockBehavior.Strict for the repository mock?
    When an unexpected call is itself the defect, for example a handler that must not touch the repository for an empty code. Strict mode throws `MockException` on any call without a setup, at the cost of having to set up every legitimate call.
  • How do you make the coupon lookup fail to test the handler's error path?
    Configure `Setup(r => r.FindAsync("SPRING10", It.IsAny<CancellationToken>())).ThrowsAsync(new TimeoutException())`, or return `null` with `ReturnsAsync((Coupon?)null)` for the not-found branch, then assert on the handler's result and that `PublishAsync` was verified with `Times.Never()`.

  • A Moq mock throws on any call you did not set up.
  • You can Setup or Verify ILogger.LogWarning directly on a Moq logger mock.
  • CancellationToken.None in a Setup matches whatever token the handler passes.
  • Times.Once() passes as long as the method was called at least once.
  • Parameterless mock.Verify() checks every call the test made.
open as a page

In an ASP.NET Core 10 unit test, how do you stub HttpClient responses for a grocery app's loyalty-points client without calling the real API?

level: middleimportance: must knowfreq 60%

basics

~20 s

Give the client an HttpClient built on a stub HttpMessageHandler whose SendAsync returns canned responses. HttpClient's GetAsync and PostAsync are not virtual, so mocking HttpClient itself fails; the handler is the seam every request passes through.

open as a page

In an ASP.NET Core 10 unit test, why can't Moq verify logger.LogWarning(...) directly, and what does FakeLogger<T> offer instead?

level: middleimportance: should knowfreq 40%

basics

~10 s

LogWarning is an extension method that calls ILogger.Log<TState>, so Moq rejects it with NotSupportedException. FakeLogger<T> from Microsoft.Extensions.Diagnostics.Testing records each entry as a FakeLogRecord with level, message, exception and structured state to assert on.

open as a page

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%

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

open as a page

How do you unit test an ASP.NET Core 10 middleware or filter in a grocery app with DefaultHttpContext, and what does that context leave out?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Build a DefaultHttpContext with the path, headers and services the code reads, pass a lambda as the next RequestDelegate, call InvokeAsync, then assert on status, headers, Items and whether next ran. Replace Response.Body with a MemoryStream to read output.

open as a page

In an ASP.NET Core 10 grocery app, how do you unit test that a coupon expires at midnight by using TimeProvider and FakeTimeProvider?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Make the coupon service read time from an injected TimeProvider, register TimeProvider.System in the app, and in tests pass a FakeTimeProvider set just before midnight; assert the coupon works, Advance past midnight, and assert it is rejected.

open as a page