Introduction
In the previous lesson, we explored testable code design and Dependency Injection. In this lesson, we will learn how to control constructor-injected dependencies during a test. We will use Moq, a widely used mocking library in the .NET ecosystem.
A service that connects to a real database, reads the system clock, sends an email, or calls a remote HTTP service can make unit tests slow, fragile, and dependent on the environment. Moq allows us to create controlled replacements for these dependencies, define return values for individual scenarios, and verify whether important calls occurred.
Our example will use an order-creation application. The order service depends on a repository, a clock provider, a messaging service, and an external inventory client. The goal is to test order-creation behavior while keeping all four dependencies isolated from their production implementations.
Mocks, stubs, and test doubles
Objects used instead of real dependencies in tests are commonly called test doubles. Several related terms are used:
- Stub: Supplies controlled data to the system under test. For example, a repository that returns a known order.
- Mock: Helps verify whether a method was called and how many times it was called.
- Fake: A simplified but working alternative implementation. An in-memory repository is an example.
Moq creates mock objects technically, but the same object can behave like a stub when it is used only to return data. The purpose in the test matters more than the class name. When a test checks the resulting state, it follows a state-based approach. When it checks an important collaboration, it follows an interaction-based approach.
The application dependencies
First, define the interfaces used by the service. In the production application, their implementations might use a database, the system clock, a messaging infrastructure, and an HTTP client.
public interface IOrderRepository { Task<Order?> GetByIdAsync(Guid id, CancellationToken cancellationToken); Task AddAsync(Order order, CancellationToken cancellationToken); } public interface IClock { DateTimeOffset UtcNow { get; } } public interface IMessagePublisher { Task PublishAsync(OrderCreatedMessage message, CancellationToken cancellationToken); } public interface IInventoryClient { Task<bool> HasStockAsync( Guid productId, int quantity, CancellationToken cancellationToken); }
Use the following simple domain models and result type:
public sealed record Order( Guid Id, Guid ProductId, int Quantity, DateTimeOffset CreatedAt); public sealed record OrderCreatedMessage(Guid OrderId); public sealed record CreateOrderResult( bool Succeeded, Guid? OrderId, string? Error) { public static CreateOrderResult Success(Guid id) => new(true, id, null); public static CreateOrderResult Failure(string error) => new(false, null, error); }
Now create the service that receives all four dependencies through constructor injection:
public sealed class OrderService { private readonly IOrderRepository _repository; private readonly IClock _clock; private readonly IMessagePublisher _publisher; private readonly IInventoryClient _inventoryClient; public OrderService( IOrderRepository repository, IClock clock, IMessagePublisher publisher, IInventoryClient inventoryClient) { _repository = repository; _clock = clock; _publisher = publisher; _inventoryClient = inventoryClient; } public async Task<CreateOrderResult> CreateAsync( Guid productId, int quantity, CancellationToken cancellationToken = default) { if (quantity <= 0) { return CreateOrderResult.Failure("Quantity must be greater than zero."); } var hasStock = await _inventoryClient.HasStockAsync( productId, quantity, cancellationToken); if (!hasStock) { return CreateOrderResult.Failure("Insufficient stock."); } var order = new Order( Guid.NewGuid(), productId, quantity, _clock.UtcNow); await _repository.AddAsync(order, cancellationToken); await _publisher.PublishAsync( new OrderCreatedMessage(order.Id), cancellationToken); return CreateOrderResult.Success(order.Id); } }
Adding the Moq package
The test project should contain compatible versions of xUnit, FluentAssertions, and Moq. Match the package versions with the stable versions used by your solution. To add Moq from the command line, use:
dotnet add Tests package Moq
Then add the required namespaces to the test class:
using FluentAssertions; using Moq; using Xunit;
Creating the first setup
Create a mock with Mock<T>. The Object property exposes the interface instance that will be passed to the service.
var repositoryMock = new Mock<IOrderRepository>(); var clockMock = new Mock<IClock>(); var publisherMock = new Mock<IMessagePublisher>(); var inventoryMock = new Mock<IInventoryClient>();
Use Setup to define what a method or property should return. A fixed clock value makes the test independent of the machine's current time:
var createdAt = new DateTimeOffset( 2026, 10, 23, 12, 0, 0, TimeSpan.Zero); clockMock .SetupGet(x => x.UtcNow) .Returns(createdAt);
For asynchronous methods, use ReturnsAsync:
inventoryMock .Setup(x => x.HasStockAsync( It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<CancellationToken>())) .ReturnsAsync(true);
It.IsAny<T>() accepts any value for a parameter. For a more precise expectation, use It.Is<T>:
inventoryMock .Setup(x => x.HasStockAsync( productId, It.Is<int>(quantity => quantity == 2), It.IsAny<CancellationToken>())) .ReturnsAsync(true);
Testing the successful scenario
Now test that the service checks inventory, saves the order, and publishes a message:
[Fact] public async Task CreateAsync_WithAvailableStock_SavesOrderAndPublishesMessage() { // Arrange var productId = Guid.NewGuid(); var createdAt = new DateTimeOffset( 2026, 10, 23, 12, 0, 0, TimeSpan.Zero); var repositoryMock = new Mock<IOrderRepository>(); var clockMock = new Mock<IClock>(); var publisherMock = new Mock<IMessagePublisher>(); var inventoryMock = new Mock<IInventoryClient>(); clockMock.SetupGet(x => x.UtcNow).Returns(createdAt); inventoryMock .Setup(x => x.HasStockAsync( productId, 2, It.IsAny<CancellationToken>())) .ReturnsAsync(true); var service = new OrderService( repositoryMock.Object, clockMock.Object, publisherMock.Object, inventoryMock.Object); // Act var result = await service.CreateAsync(productId, 2); // Assert result.Succeeded.Should().BeTrue(); result.OrderId.Should().NotBeNull(); repositoryMock.Verify(x => x.AddAsync( It.Is<Order>(order => order.ProductId == productId && order.Quantity == 2 && order.CreatedAt == createdAt), It.IsAny<CancellationToken>()), Times.Once); publisherMock.Verify(x => x.PublishAsync( It.Is<OrderCreatedMessage>(message => message.OrderId == result.OrderId), It.IsAny<CancellationToken>()), Times.Once); }
Here, Setup defines behavior, while Verify checks an interaction. The It.Is expression inspects the order passed to the repository. This verifies not only that AddAsync was called, but also that it received the correct product, quantity, and timestamp.
Invocation verification options
Moq provides several Times options for checking invocation counts:
- Times.Once: Exactly one invocation.
- Times.Never: No invocation.
- Times.AtMostOnce: Zero or one invocation.
- Times.Exactly(2): Exactly two invocations.
If inventory is unavailable, neither the repository nor the messaging service should be called:
[Fact] public async Task CreateAsync_WhenStockIsUnavailable_DoesNotSaveOrPublish() { // Arrange var productId = Guid.NewGuid(); var repositoryMock = new Mock<IOrderRepository>(); var clockMock = new Mock<IClock>(); var publisherMock = new Mock<IMessagePublisher>(); var inventoryMock = new Mock<IInventoryClient>(); inventoryMock .Setup(x => x.HasStockAsync( productId, 3, It.IsAny<CancellationToken>())) .ReturnsAsync(false); var service = new OrderService( repositoryMock.Object, clockMock.Object, publisherMock.Object, inventoryMock.Object); // Act var result = await service.CreateAsync(productId, 3); // Assert result.Succeeded.Should().BeFalse(); result.Error.Should().Be("Insufficient stock."); repositoryMock.Verify(x => x.AddAsync( It.IsAny<Order>(), It.IsAny<CancellationToken>()), Times.Never); publisherMock.Verify(x => x.PublishAsync( It.IsAny<OrderCreatedMessage>(), It.IsAny<CancellationToken>()), Times.Never); }
Inspecting an argument with Callback
Sometimes a verification expression becomes difficult to read. Use Callback to capture the object passed to a dependency:
Order? savedOrder = null; repositoryMock .Setup(x => x.AddAsync( It.IsAny<Order>(), It.IsAny<CancellationToken>())) .Callback<Order, CancellationToken>( (order, _) => savedOrder = order) .Returns(Task.CompletedTask);
After the system under test runs, make more detailed FluentAssertions checks against savedOrder. Use Callback only when it improves the test. For a simple value check, a direct Verify with It.Is is usually clearer.
Error and exception scenarios
The behavior of the application must also be tested when an external service fails. Moq supports Throws for synchronous methods and ThrowsAsync for asynchronous methods:
inventoryMock .Setup(x => x.HasStockAsync( productId, 1, It.IsAny<CancellationToken>())) .ThrowsAsync(new HttpRequestException("Inventory unavailable"));
If the service catches the exception and returns a special result, assert that result. If the exception is expected to propagate, verify its type with FluentAssertions:
var action = () => service.CreateAsync(productId, 1); await action.Should() .ThrowAsync<HttpRequestException>();
In an exception test, also verify that the repository or publisher was not called. This demonstrates that the failed workflow did not continue with partial side effects.
Strict and Loose mock behavior
By default, Moq creates mocks with Loose behavior. Members without setups usually return default values. This is convenient, but an omitted setup can sometimes allow a test to pass with behavior that does not represent the intended scenario.
var inventoryMock = new Mock<IInventoryClient>( MockBehavior.Strict);
With Strict behavior, an unexpected call without a setup throws an exception. This can be useful for small, important services. However, making every dependency Strict can couple tests too tightly to implementation details. Explicitly set up and verify meaningful business interactions instead of verifying every technical call.
Common mistakes
- Verifying every invocation: This locks the test to implementation details. Focus on calls that affect business behavior.
- Using the real clock: Reading DateTimeOffset.UtcNow directly inside the service makes tests unstable. Inject an IClock instead.
- Matching parameters too broadly: Because It.IsAny accepts everything, verify important parameters with a real predicate.
- Sharing mocks between tests: Invocation history and setups can leak between tests. Create fresh mocks per test or reset them deliberately.
- Mocking concrete classes unnecessarily: Prefer separating behavior behind interfaces and injecting external dependencies through those interfaces.
- Using real HTTP or database infrastructure in a unit test: This moves the test toward integration testing. We will cover real infrastructure separately in later lessons.
Practice exercise
Implement the following scenarios yourself:
- Write a test that returns a failure result when the quantity is zero.
- Verify that IInventoryClient, IOrderRepository, and IMessagePublisher are not called in that scenario.
- In the successful scenario, verify that the same CancellationToken is passed to all dependencies.
- Verify that the message passed to PublishAsync contains the identifier of the saved order.
Use names that describe behavior. For example, CreateAsync_WhenQuantityIsZero_ReturnsValidationFailure clearly communicates the scenario and expected result.
Conclusion
In this lesson, we replaced real dependencies with controlled test doubles using Moq. We used Setup to define return values and exception behavior, and used Verify, Times, and It.Is to check important collaborations. By isolating the repository, clock provider, messaging service, and external service, we made the tests fast and repeatable.
Good mock usage does not mean verifying every internal detail of a class. The goal is to protect important business behavior without requiring real infrastructure. In the next stage, we will move this approach to the ASP.NET Core API layer and examine how integration tests work with WebApplicationFactory.