Mocking in .NET

MSDN Tutorial

Table of Contents

What is Mocking?

Mocking allows you to replace real dependencies with test‑doubles, providing controlled behavior and isolation for unit tests. It helps verify interactions, return predefined results, and avoid costly external resources.

Installing Moq

For .NET projects, Moq is one of the most popular frameworks.

dotnet add package Moq --version 4.20.0

Simple Mock Example

Consider an IUserRepository that fetches users from a database. We'll mock it to test UserService.

public interface IUserRepository
{
    User GetById(int id);
}

public class UserService
{
    private readonly IUserRepository _repo;
    public UserService(IUserRepository repo) => _repo = repo;

    public string GetUserName(int id)
    {
        var user = _repo.GetById(id);
        return user?.Name ?? "Unknown";
    }
}

// Unit Test
var mockRepo = new Mock<IUserRepository>();
mockRepo.Setup(r => r.GetById(It.IsAny<int>()))
        .Returns(new User { Id = 1, Name = "Alice" });

var service = new UserService(mockRepo.Object);
var result = service.GetUserName(1);
Assert.Equal("Alice", result);

Verifying Calls & Callbacks

You can verify that certain methods were called a specific number of times, or capture arguments using callbacks.

// Verify method call count
mockRepo.Verify(r => r.GetById(It.IsAny<int>()), Times.Once);

// Capture argument
User capturedUser = null;
mockRepo.Setup(r => r.Save(It.IsAny<User>()))
        .Callback<User>(u => capturedUser = u);

// After invoking Save
Assert.NotNull(capturedUser);
Assert.Equal("Bob", capturedUser.Name);

Further Reading