Moq
01 / 02

Moq Fundamentals: Setup, Verify & Argument Matching

Moq: Setup, Verify & Argument Matching

Moq is a popular open-source mocking library for .NET, used to create fake implementations of interfaces (or virtual class members) for unit testing. It isolates the code under test from its real dependencies -- a database repository, an external API client -- letting a test run fast and deterministically.

Creating a Mock & Configuring Behavior

var mockRepo = new Mock<IUserRepository>();

// Setup() defines what the mocked method returns when called
mockRepo.Setup(r => r.GetUserById(1))
        .Returns(new User { Id = 1, Name = "Alice" });

// .Object is the actual fake IUserRepository implementation --
// pass it to the class under test just like a real dependency
var service = new UserService(mockRepo.Object);

var user = service.GetUser(1);
Assert.Equal("Alice", user.Name);

Argument Matching with It.IsAny<T>()

// Returns defaultUser regardless of WHICH id is passed in
mockRepo.Setup(r => r.GetUserById(It.IsAny<int>()))
        .Returns(defaultUser);

// Different setups per specific argument value are also supported
mockRepo.Setup(r => r.GetUserById(1)).Returns(alice);
mockRepo.Setup(r => r.GetUserById(2)).Returns(bob);

Verifying Interactions

// Testing that the code under test correctly INTERACTS with a
// dependency -- not just what it returns, but whether/how it was called
service.SaveUser(newUser);

mockRepo.Verify(r => r.Save(It.IsAny<User>()), Times.Once);
mockLogger.Verify(l => l.LogError(It.IsAny<string>()), Times.Never);

Simulating Failures with .Throws()

// Test error-handling logic by making the mock throw --
// no real, genuinely-failing dependency needed
mockRepo.Setup(r => r.Save(It.IsAny<User>()))
        .Throws<InvalidOperationException>();

var result = service.TrySaveUser(newUser);
Assert.False(result.Success);

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free