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 MoqVia Package Manager Console (Visual Studio)
Install-Package MoqVia 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:
new Mock<IUserRepository>()— create a mock object for the interface..Setup(...)— configure behavior: whenGetUserById(1)is called, return the user Alice.mockRepo.Object— get the "fake" object that is passed to the service.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
Also in library
Event Bus and Observer Pattern in Java: A Guide with Examples
Redis client for Kotlin: Lettuce and Kreds — comparison and examples
Working with Dates in Go (Golang): Overview of Libraries and Packages
Testing in JavaScript (Node.js): Frameworks and Tools