C# / .NET Compendium PLEN
.NET / C# / Testing

Moq - mocking dependencies in tests

Basic usage - creating a mock and configuring its behaviour

public interface IOrderRepository
{
    Task<Order> GetByIdAsync(int id);
    Task SaveAsync(Order order);
}

[Fact]
public async Task GetOrder_ExistingId_ReturnsOrder()
{
    // Arrange
    var mockRepository = new Mock<IOrderRepository>();
    mockRepository
        .Setup(r => r.GetByIdAsync(1))
        .ReturnsAsync(new Order { Id = 1, CustomerName = "Jan" });

    var service = new OrderService(mockRepository.Object); // .Object - the actual implementation of the mock

    // Act
    var order = await service.GetOrderAsync(1);

    // Assert
    Assert.Equal("Jan", order.CustomerName);
}

Instead of calling a real repository (which would require a real database), you create a stand-in (a mock) that returns predefined data - thanks to this the test is fast, deterministic and doesn't depend on external infrastructure.

It.IsAny<T>() - matching any argument

mockRepository
    .Setup(r => r.GetByIdAsync(It.IsAny<int>())) // dopasuje DOWOLNE id
    .ReturnsAsync(new Order { Id = 999, CustomerName = "Test" });

Useful when you don't want to check a specific argument value, but only care about the mock's general behaviour.

Verify() - checking that a method was called

[Fact]
public async Task CreateOrder_ValidOrder_CallsSaveOnce()
{
    var mockRepository = new Mock<IOrderRepository>();
    var service = new OrderService(mockRepository.Object);

    await service.CreateOrderAsync(new Order { CustomerName = "Jan" });

    mockRepository.Verify(r => r.SaveAsync(It.IsAny<Order>()), Times.Once); // exactly ONCE
    mockRepository.Verify(r => r.SaveAsync(It.IsAny<Order>()), Times.Never); // checks that it was NOT called
}

This lets you test behaviour, not just the returned value - e.g. "did the service actually try to save the order", regardless of what the repository returned.

Mocking exceptions - testing error handling

[Fact]
public async Task GetOrder_RepositoryThrows_PropagatesException()
{
    var mockRepository = new Mock<IOrderRepository>();
    mockRepository
        .Setup(r => r.GetByIdAsync(It.IsAny<int>()))
        .ThrowsAsync(new InvalidOperationException("Database error"));

    var service = new OrderService(mockRepository.Object);

    await Assert.ThrowsAsync<InvalidOperationException>(() => service.GetOrderAsync(1));
}

Mocking a sequence of calls - different values on successive calls

mockRepository
    .SetupSequence(r => r.GetByIdAsync(1))
    .ReturnsAsync(new Order { Status = "Pending" })  // the first call
    .ReturnsAsync(new Order { Status = "Shipped" });  // the second call

Callback - running additional logic when the mock is called

var savedOrders = new List<Order>();

mockRepository
    .Setup(r => r.SaveAsync(It.IsAny<Order>()))
    .Callback<Order>(order => savedOrders.Add(order)) // you capture the argument and do something with it
    .Returns(Task.CompletedTask);

await service.CreateOrderAsync(new Order { CustomerName = "Jan" });

Assert.Single(savedOrders);
Assert.Equal("Jan", savedOrders[0].CustomerName);

Mocking dependencies with DI - integrating with what we already know

This is a natural extension of the constructor injection we discussed earlier - a mock is simply an alternative implementation of an interface, injected through the constructor just like in the real application:

public class OrderService : IOrderService
{
    private readonly IOrderRepository _repository;
    private readonly ILogger<OrderService> _logger;

    public OrderService(IOrderRepository repository, ILogger<OrderService> logger)
    {
        _repository = repository;
        _logger = logger;
    }
}
[Fact]
public async Task Test()
{
    var mockRepository = new Mock<IOrderRepository>();
    var mockLogger = new Mock<ILogger<OrderService>>(); // you CAN mock even ILogger

    var service = new OrderService(mockRepository.Object, mockLogger.Object); // EXACTLY the same constructor
}

This is precisely why DI through the constructor (rather than a Service Locator or Ambient Context) is so valuable for testability - every dependency is explicitly visible and easily replaceable with a mock, without any tricks.

Summary of the key Moq methods

Method Purpose
Setup() Configuring the mock's behaviour for a specific call
Returns()/ReturnsAsync() The returned value (synchronous/asynchronous)
ThrowsAsync() Simulating throwing an exception
Verify() Checking that a method was called (and how many times)
It.IsAny<T>() Matching any argument of the given type
Callback() Running additional logic when the mock is called
SetupSequence() Different values on successive calls of the same method
Buy me a coffee