Moq for C# (.NET): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Moq and why is it needed?



Moq (pronounced as "Mock") is a popular library for creating mock objects (stubs) in C# (.NET). It is part of the unit testing ecosystem and is used to isolate the code under test from its dependencies.



In real applications, classes often depend on other classes: databases, web services, file systems, third-party service APIs. When writing unit tests, we do not want to test these external dependencies — we only want to verify the logic of our class. Moq allows you to create "fake" (mock) objects that imitate the behavior of real dependencies, but are fully controlled by the test.



Main use cases for Moq:

  • Test isolation: testing a single class without running a database or external services.
  • Interaction verification: ensuring a method was called with the correct arguments, a specific number of times.
  • Setting return values: making a dependency return the necessary data to test logic.
  • Simulating exceptions: checking how code handles errors from external systems.


Moq works with interfaces and virtual methods of classes. This is a key limitation: you cannot mock a static method or a non-virtual method.



Installing Moq



Moq is distributed via NuGet — the package manager for .NET. It can be installed in several ways:



Via .NET CLI (recommended)

dotnet add package Moq


Via Package Manager Console (Visual Studio)

Install-Package Moq


Via NuGet Package Manager UI

In Visual Studio: Right-click on project → Manage NuGet Packages → Search "Moq" → Install



Requirements: .NET Framework 4.5+ or .NET Core 2.0+ / .NET 5+



Quick start: first test with Moq



Suppose we have a repository interface and a service that uses it:



public interface IUserRepository{    User GetUserById(int id);    void SaveUser(User user);}

public class UserService{ private readonly IUserRepository _repository;

public UserService(IUserRepository repository) { _repository = repository; }

public string GetUserName(int userId) { var user = _repository.GetUserById(userId); return user?.Name ?? "Unknown"; }}

public class User{ public int Id { get; set; } public string Name { get; set; }}


Now let's write a test using Moq:



using Moq;using Xunit;

public class UserServiceTests{ [Fact] public void GetUserName_WhenUserExists_ReturnsUserName() { // Arrange var mockRepo = new Mock<IUserRepository>(); mockRepo.Setup(repo => repo.GetUserById(1)) .Returns(new User { Id = 1, Name = "Alice" });

var service = new UserService(mockRepo.Object);

// Act var result = service.GetUserName(1);

// Assert Assert.Equal("Alice", result); mockRepo.Verify(repo => repo.GetUserById(1), Times.Once); }}


Example breakdown:

  1. new Mock<IUserRepository>() — create a mock object for the interface.
  2. .Setup(...) — configure behavior: when GetUserById(1) is called, return the user Alice.
  3. mockRepo.Object — get the "fake" object that is passed to the service.
  4. mockRepo.Verify(...) — verify that the method was called exactly once.


Main methods and functions of Moq



1. Mock<T>.Setup()

What it does: Configures the behavior of a method

Recommendations