Mocks and test doubles
suggest changeA test double is an object that stands in for a real dependency during a test. You use one when the real thing is slow (a database), non-deterministic (the clock, random numbers), has side effects (sending email, charging a card) or simply doesn't exist yet.
"Mock" is often used for all of them, but there are different kinds, and knowing which one you need keeps tests simple:
| Kind | What it does | Example |
|---|---|---|
| dummy | passed only to satisfy a parameter, never really used | NullLogger<T>.Instance |
| stub | returns canned answers | a clock that always says 9:00 |
| spy | records calls so the test can check them afterwards | an email sender that stores messages in a list |
| mock | is told up front which calls to expect and checks them | Verify(...) / Received(...) in a mocking library |
| fake | a working but simplified implementation | an in-memory repository |
Test doubles only work if the code under test lets you swap dependencies. In C# that means receiving them through the constructor as interfaces (or abstract classes with virtual members) instead of creating them with new inside the class. See Dependency Injection.
Examples use xUnit v3 on .NET 10, set up as in Unit testing.
The code under test
A password-reset service with four dependencies: a user repository, an email sender, the clock and a logger.
using System.Security.Cryptography;
using Microsoft.Extensions.Logging;
namespace Accounts;
public class User
{
public required int Id { get; init; }
public required string Email { get; init; }
public string? ResetToken { get; set; }
public DateTimeOffset? ResetExpires { get; set; }
}
public interface IUserRepository
{
Task<User?> FindAsync(int id);
Task SaveAsync(User user);
}
public interface IEmailSender
{
Task SendAsync(string to, string subject, string body);
}
public class PasswordResetService(
IUserRepository users,
IEmailSender email,
TimeProvider time,
ILogger<PasswordResetService> logger)
{
public static readonly TimeSpan TokenLifetime = TimeSpan.FromHours(1);
public async Task<bool> RequestResetAsync(int userId)
{
var user = await users.FindAsync(userId);
if (user is null)
{
logger.LogWarning("Password reset for unknown user {UserId}", userId);
return false;
}
var now = time.GetUtcNow();
// a token that is still valid: don't send another email
if (user.ResetExpires > now)
return false;
user.ResetToken = Convert.ToHexString(RandomNumberGenerator.GetBytes(8));
user.ResetExpires = now + TokenLifetime;
await users.SaveAsync(user);
await email.SendAsync(user.Email, "Reset your password",
$"Your code: {user.ResetToken}");
logger.LogInformation("Reset token sent to user {UserId}", userId);
return true;
}
public async Task<bool> ResetAsync(int userId, string token)
{
var user = await users.FindAsync(userId);
if (user?.ResetToken is null || user.ResetToken != token)
return false;
if (time.GetUtcNow() >= user.ResetExpires)
return false;
user.ResetToken = null;
user.ResetExpires = null;
await users.SaveAsync(user);
return true;
}
}
TimeProvider is the built-in .NET abstraction over the clock. Production code passes TimeProvider.System; tests pass something they control.
Hand-written test doubles
For small interfaces, writing the doubles by hand is often the clearest option. There is no library to learn, and the test reads like normal code:
using Accounts;
using Microsoft.Extensions.Logging.Abstractions;
// fake: a working, simplified implementation
class InMemoryUserRepository : IUserRepository
{
private readonly Dictionary<int, User> _users = [];
public void Add(User user) => _users[user.Id] = user;
public Task<User?> FindAsync(int id) =>
Task.FromResult(_users.GetValueOrDefault(id));
public Task SaveAsync(User user)
{
_users[user.Id] = user;
return Task.CompletedTask;
}
}
// spy: records calls so the test can check them afterwards
class SpyEmailSender : IEmailSender
{
public List<(string To, string Subject, string Body)> Sent { get; } = [];
public Task SendAsync(string to, string subject, string body)
{
Sent.Add((to, subject, body));
return Task.CompletedTask;
}
}
// stub: returns canned answers
class StubTimeProvider(DateTimeOffset now) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => now;
}
public class HandWrittenTests
{
static readonly DateTimeOffset Now = new(2026, 10, 17, 9, 0, 0, TimeSpan.Zero);
private readonly InMemoryUserRepository _users = new();
private readonly SpyEmailSender _email = new();
private readonly PasswordResetService _service;
public HandWrittenTests()
{
_users.Add(new User { Id = 1, Email = "ann@example.com" });
// dummy: NullLogger satisfies the constructor and does nothing
_service = new PasswordResetService(_users, _email, new StubTimeProvider(Now),
NullLogger<PasswordResetService>.Instance);
}
[Fact]
public async Task RequestReset_EmailsTokenAndStoresIt()
{
Assert.True(await _service.RequestResetAsync(1));
var user = (await _users.FindAsync(1))!;
Assert.Equal(Now.AddHours(1), user.ResetExpires);
var mail = Assert.Single(_email.Sent);
Assert.Equal("ann@example.com", mail.To);
Assert.Equal($"Your code: {user.ResetToken}", mail.Body);
}
[Fact]
public async Task RequestReset_TwiceSendsOneEmail()
{
await _service.RequestResetAsync(1);
Assert.False(await _service.RequestResetAsync(1));
Assert.Single(_email.Sent);
}
[Fact]
public async Task Reset_WithCorrectToken_ClearsIt()
{
await _service.RequestResetAsync(1);
var token = (await _users.FindAsync(1))!.ResetToken!;
Assert.False(await _service.ResetAsync(1, "WRONG"));
Assert.True(await _service.ResetAsync(1, token));
Assert.Null((await _users.FindAsync(1))!.ResetToken);
}
}
The in-memory fake is the most useful of these. Because it really stores users, the tests check behaviour ("after a reset the token is gone") rather than which methods were called. You can refactor the service, for example to save once instead of twice, without touching the tests.
The fake is also reusable: write it once and every test that needs a repository can use it.
NSubstitute
When an interface has many members, or you need different answers in every test, hand-written doubles get tedious. A mocking library generates the implementation at run time. NSubstitute has the most concise syntax:
dotnet add package NSubstitute
dotnet add package NSubstitute.Analyzers.CSharp
The analyzers package is optional but catches common mistakes at compile time (more on that below).
Substitute.For<T>() creates an object that implements T. Calling a member followed by .Returns(...) configures it; .Received() checks that a call happened:
using Accounts;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
public class NSubstituteTests
{
static readonly DateTimeOffset Now = new(2026, 10, 17, 9, 0, 0, TimeSpan.Zero);
private readonly IUserRepository _users = Substitute.For<IUserRepository>();
private readonly IEmailSender _email = Substitute.For<IEmailSender>();
private readonly TimeProvider _time = Substitute.For<TimeProvider>();
private readonly PasswordResetService _service;
public NSubstituteTests()
{
_time.GetUtcNow().Returns(Now);
_service = new PasswordResetService(_users, _email, _time,
NullLogger<PasswordResetService>.Instance);
}
[Fact]
public async Task RequestReset_SavesUserAndSendsEmail()
{
var ann = new User { Id = 1, Email = "ann@example.com" };
_users.FindAsync(1).Returns(ann);
Assert.True(await _service.RequestResetAsync(1));
await _users.Received(1).SaveAsync(ann);
await _email.Received(1).SendAsync(
"ann@example.com",
"Reset your password",
Arg.Is<string>(body => body.StartsWith("Your code: ")));
}
[Fact]
public async Task RequestReset_UnknownUser_SendsNothing()
{
// unconfigured async methods return a completed Task with default value: null
Assert.False(await _service.RequestResetAsync(42));
await _users.DidNotReceive().SaveAsync(Arg.Any<User>());
await _email.DidNotReceiveWithAnyArgs().SendAsync(default!, default!, default!);
}
}
Things to note:
_users.FindAsync(1).Returns(ann)works on aTask<User?>method: NSubstitute wrapsannin a completed task for you.- Members you don't configure return defaults:
0,null, empty strings forstring, empty arrays, completed tasks, and for interface return types, another substitute. TimeProvideris an abstract class, not an interface. Substituting for it works becauseGetUtcNowisvirtual.Received(1)means exactly once;Received()means at least once.awaittheReceived()call on async methods. It does nothing at run time, but it silences the compiler warning about an unawaited task.
Argument matchers
Literal values match by Equals. For anything else use Arg:
| Matcher | Matches |
|---|---|
Arg.Any<T>() |
any value of type T, including null |
Arg.Is<T>(x => ...) |
values for which the predicate is true |
Arg.Is(value) |
a specific value (same as passing it directly) |
Arg.Do<T>(x => ...) |
any value, and runs the action with it |
ReturnsForAnyArgs, ReceivedWithAnyArgs and DidNotReceiveWithAnyArgs ignore all arguments, which is why default! placeholders are fine there.
Computed results, captured arguments and callbacks
Returns accepts a function that receives the call info. Arg.Do and When(...).Do(...) let you capture what the code passed in:
[Fact]
public async Task RequestReset_EmailContainsSavedToken()
{
_users.FindAsync(Arg.Any<int>())
.Returns(ci => new User { Id = ci.Arg<int>(), Email = "x@example.com" });
string? savedToken = null;
await _users.SaveAsync(Arg.Do<User>(u => savedToken = u.ResetToken));
string? body = null;
_email.When(e => e.SendAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()))
.Do(ci => body = ci.ArgAt<string>(2));
await _service.RequestResetAsync(7);
Assert.NotNull(savedToken);
Assert.Equal($"Your code: {savedToken}", body);
}
The token is random, so the test can't know it in advance. Capturing it from the SaveAsync call and comparing it with the email body checks that the user gets the same token that was stored.
Consecutive values are passed as extra arguments to Returns. Here the first GetUtcNow call (inside RequestResetAsync) returns 9:00 and the second (inside ResetAsync) returns 10:01:
[Fact]
public async Task Reset_ExpiredToken_Fails()
{
var ann = new User { Id = 1, Email = "ann@example.com" };
_users.FindAsync(1).Returns(ann);
_time.GetUtcNow().Returns(Now, Now.AddMinutes(61));
await _service.RequestResetAsync(1);
Assert.False(await _service.ResetAsync(1, ann.ResetToken!));
}
Simulating failures
Error paths are where test doubles shine: making a real SMTP server time out on demand is hard, making a substitute do it is one line.
[Fact]
public async Task RequestReset_EmailFailure_Propagates()
{
_users.FindAsync(1).Returns(new User { Id = 1, Email = "ann@example.com" });
_email.SendAsync(default!, default!, default!)
.ReturnsForAnyArgs(Task.FromException(new TimeoutException("SMTP timeout")));
var ex = await Assert.ThrowsAsync<TimeoutException>(() => _service.RequestResetAsync(1));
Assert.Equal("SMTP timeout", ex.Message);
}
[Fact]
public async Task Reset_DatabaseDown_Throws()
{
_users.FindAsync(1).ThrowsAsync(new InvalidOperationException("db down"));
await Assert.ThrowsAsync<InvalidOperationException>(() => _service.ResetAsync(1, "T"));
}
Throws and ThrowsAsync come from the NSubstitute.ExceptionExtensions namespace. ThrowsAsync returns a faulted task, which is how real async methods fail. Throws on an async method throws synchronously, before a task exists, which real code rarely does.
Failure messages
When a Received check fails, NSubstitute lists the calls that did happen and marks the arguments that didn't match:
await _email.Received().SendAsync("bob@example.com", Arg.Any<string>(), Arg.Any<string>());
NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
SendAsync("bob@example.com", any String, any String)
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
SendAsync(*"ann@example.com"*, "Reset your password", "Your code: 693E25D13C343743")
Moq
Moq is the other widely used library. It does the same things with a different style: you wrap the type in Mock<T>, configure it with lambda expressions and pass .Object to the code under test.
dotnet add package Moq
using Accounts;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
public class MoqTests
{
static readonly DateTimeOffset Now = new(2026, 10, 17, 9, 0, 0, TimeSpan.Zero);
private readonly Mock<IUserRepository> _users = new();
private readonly Mock<IEmailSender> _email = new();
private readonly Mock<TimeProvider> _time = new();
private readonly PasswordResetService _service;
public MoqTests()
{
_time.Setup(t => t.GetUtcNow()).Returns(Now);
_service = new PasswordResetService(_users.Object, _email.Object, _time.Object,
NullLogger<PasswordResetService>.Instance);
}
[Fact]
public async Task RequestReset_SavesUserAndSendsEmail()
{
var ann = new User { Id = 1, Email = "ann@example.com" };
_users.Setup(r => r.FindAsync(1)).ReturnsAsync(ann);
Assert.True(await _service.RequestResetAsync(1));
_users.Verify(r => r.SaveAsync(ann), Times.Once);
_email.Verify(e => e.SendAsync(
"ann@example.com",
"Reset your password",
It.Is<string>(body => body.StartsWith("Your code: "))), Times.Once);
_email.VerifyNoOtherCalls();
}
[Fact]
public async Task Callback_CapturesArgument()
{
_users.Setup(r => r.FindAsync(It.IsAny<int>()))
.ReturnsAsync((int id) => new User { Id = id, Email = "x@example.com" });
User? saved = null;
_users.Setup(r => r.SaveAsync(It.IsAny<User>()))
.Callback<User>(u => saved = u)
.Returns(Task.CompletedTask);
await _service.RequestResetAsync(7);
Assert.Equal(7, saved?.Id);
Assert.Equal(Now.AddHours(1), saved?.ResetExpires);
}
}
The two libraries map almost one to one:
| NSubstitute | Moq |
|---|---|
Substitute.For<T>() |
new Mock<T>(), then .Object |
x.M(1).Returns(v) |
m.Setup(x => x.M(1)).Returns(v) / .ReturnsAsync(v) |
Arg.Any<T>(), Arg.Is<T>(...) |
It.IsAny<T>(), It.Is<T>(...) |
x.Received(1).M(1) |
m.Verify(x => x.M(1), Times.Once) |
x.DidNotReceive().M(1) |
m.Verify(x => x.M(1), Times.Never) |
x.M(1).ThrowsAsync(e) |
m.Setup(x => x.M(1)).ThrowsAsync(e) |
When(...).Do(...), Arg.Do |
.Callback(...) |
By default a Moq mock is loose: unconfigured calls return defaults, like NSubstitute. With MockBehavior.Strict, every call needs a Setup or it throws:
[Fact]
public async Task Strict_FailsOnUnexpectedCall()
{
var users = new Mock<IUserRepository>(MockBehavior.Strict);
users.Setup(r => r.FindAsync(1)).ReturnsAsync(new User { Id = 1, Email = "a@b.c" });
var service = new PasswordResetService(users.Object, _email.Object, _time.Object,
NullLogger<PasswordResetService>.Instance);
await Assert.ThrowsAsync<MockException>(() => service.RequestResetAsync(1));
}
IUserRepository.SaveAsync(User) invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
Strict mocks sound safer but make tests brittle: every harmless new call in the production code breaks them. Prefer loose doubles and verify only the calls that matter.
Built-in fakes for time and logging
Microsoft ships ready-made fakes for two dependencies almost every service has.
dotnet add package Microsoft.Extensions.TimeProvider.Testing
dotnet add package Microsoft.Extensions.Diagnostics.Testing
FakeTimeProvider is a clock you move forward with Advance. It also fires timers and completes Task.Delay calls made through the provider when their time comes. FakeLogger<T> collects log records so you can assert on them:
using Accounts;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Time.Testing;
public class BuiltInFakesTests
{
private readonly InMemoryUserRepository _users = new();
private readonly SpyEmailSender _email = new();
private readonly FakeTimeProvider _time = new(new DateTimeOffset(2026, 10, 17, 9, 0, 0, TimeSpan.Zero));
private readonly FakeLogger<PasswordResetService> _logger = new();
private readonly PasswordResetService _service;
public BuiltInFakesTests()
{
_users.Add(new User { Id = 1, Email = "ann@example.com" });
_service = new PasswordResetService(_users, _email, _time, _logger);
}
[Fact]
public async Task Token_ExpiresAfterOneHour()
{
await _service.RequestResetAsync(1);
var token = (await _users.FindAsync(1))!.ResetToken!;
_time.Advance(TimeSpan.FromMinutes(59));
Assert.False(await _service.RequestResetAsync(1)); // still valid, no new email
_time.Advance(TimeSpan.FromMinutes(1));
Assert.False(await _service.ResetAsync(1, token)); // expired
Assert.True(await _service.RequestResetAsync(1)); // can ask again
Assert.Equal(2, _email.Sent.Count);
}
[Fact]
public async Task UnknownUser_LogsWarning()
{
await _service.RequestResetAsync(99);
var record = _logger.LatestRecord;
Assert.Equal(LogLevel.Warning, record.Level);
Assert.Equal("Password reset for unknown user 99", record.Message);
Assert.Equal(1, _logger.Collector.Count);
}
}
record.Message is the formatted message. record.StructuredState has the individual values; for the warning above it contains:
[UserId, 99], [{OriginalFormat}, Password reset for unknown user {UserId}]
Checking the structured value (UserId = 99) is more robust than checking the message text, which tends to get reworded.
Faking HttpClient
HttpClient isn't an interface and its methods aren't virtual, so mocking libraries can't replace it. They don't need to: HttpClient sends every request through an HttpMessageHandler, and you can pass your own handler to its constructor.
using System.Net;
using System.Net.Http.Json;
public record Rate(string Currency, decimal Value);
public class RatesClient(HttpClient http)
{
public async Task<decimal?> GetRateAsync(string currency)
{
using var response = await http.GetAsync($"rates/{currency}");
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
response.EnsureSuccessStatusCode();
var rate = await response.Content.ReadFromJsonAsync<Rate>();
return rate!.Value;
}
}
class StubHandler(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
{
public List<HttpRequestMessage> Requests { get; } = [];
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Requests.Add(request);
return Task.FromResult(respond(request));
}
}
public class RatesClientTests
{
[Fact]
public async Task ParsesRate()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = JsonContent.Create(new Rate("EUR", 1.08m)),
});
var client = new RatesClient(new HttpClient(handler) { BaseAddress = new Uri("https://api.example.com/") });
Assert.Equal(1.08m, await client.GetRateAsync("EUR"));
var request = Assert.Single(handler.Requests);
Assert.Equal("https://api.example.com/rates/EUR", request.RequestUri!.ToString());
}
[Fact]
public async Task UnknownCurrency_ReturnsNull()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.NotFound));
var client = new RatesClient(new HttpClient(handler) { BaseAddress = new Uri("https://api.example.com/") });
Assert.Null(await client.GetRateAsync("XYZ"));
}
[Fact]
public async Task ServerError_Throws()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError));
var client = new RatesClient(new HttpClient(handler) { BaseAddress = new Uri("https://api.example.com/") });
var ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetRateAsync("EUR"));
Assert.Equal(HttpStatusCode.InternalServerError, ex.StatusCode);
}
}
No network is involved, so these tests are fast and run offline. The handler is both a stub (it returns canned responses) and a spy (it records requests).
What can't be replaced
NSubstitute and Moq create a subclass (a proxy) at run time with Castle DynamicProxy. A proxy can only override what C# lets you override, so they can replace:
- members of interfaces
abstractandvirtualmembers of non-sealed classes
They can't replace non-virtual methods, static methods, sealed classes, extension methods or constructors. Moq reports this clearly:
public class PriceList
{
public decimal Price(string sku) => 10m; // not virtual
public virtual decimal VirtualPrice(string sku) => 10m;
}
var prices = new Mock<PriceList>();
prices.Setup(p => p.Price("A")).Returns(99m);
System.NotSupportedException : Unsupported expression: p => p.Price("A")
Non-overridable members (here: PriceList.Price) may not be used in setup / verification expressions.
NSubstitute can't see the call to a non-virtual member at all. prices.Price("A").Returns(99m) throws CouldNotSetReturnDueToNoLastCallException at best. At worst, if another substitute call happened just before it, Returns silently configures that earlier call instead. This is what the analyzers package is for. It flags the line at compile time:
warning NS1000: Member Price can not be intercepted. Only interface members and virtual,
overriding, and abstract members can be intercepted.
Consider making NS1000 an error in .editorconfig (dotnet_diagnostic.NS1000.severity = error).
Extension methods are a common trap: logger.LogWarning(...) is an extension method that calls ILogger.Log<TState>(...) with an internal state type. Verifying LogWarning on a mocked ILogger is impossible, and verifying Log<TState> is awkward. Use FakeLogger instead.
If you need to replace something static, such as DateTime.Now, File.ReadAllText or Guid.NewGuid(), wrap it behind an interface or pass a delegate (Func<Guid>). For the clock and the file system there are ready-made abstractions: TimeProvider and the System.IO.Abstractions package.
Practical advice
- Fake only the edges. Replace things that are slow, non-deterministic or have side effects: network, database, file system, clock, randomness, email. Use the real implementation of your own plain classes; mocking them only tests that the code calls what it currently calls.
- Prefer state over interaction. "The user has no token after a reset" survives refactoring; "
SaveAsyncwas called exactly twice" doesn't. Verify calls only when the call itself is the result, like sending an email or charging a card. - Don't mock types you don't own. Mocking
DbContextorHttpClientinternals means guessing how they behave. Wrap them behind your own small interface, or use a real lightweight version (SQLite in-memory, a stubHttpMessageHandler) and cover the real integration with a few integration tests. - Keep setups minimal. Configure only what the test needs. Twenty lines of
Returnsbefore one assertion means the class has too many dependencies or the test checks too much. - Many doubles are a design signal. A constructor with seven interfaces is hard to test because it does too much. Split the class rather than writing heavier mocks.
- Pick one library per codebase. NSubstitute and Moq can do the same things; mixing them makes tests harder to read.
- Reuse hand-written fakes. A good in-memory fake shared by many tests is often worth more than per-test mock setups.