Overview

These notes provide links to other features of Moq not covered in other notes.

Customizing Mock Behavior

When instantiating a mock, pass the MockBehavior enum to customize the behavior:

var mock = new Mock<IService>(MockBehavior.Strict);

Behaviors:

  • Strict — throw an exception whenever a method or property is invoked without a matching configuration
  • Loose (default) — return a default value instead of throwing an exception

Callbacks

See https://docs.educationsmediagroup.com/unit-testing-csharp/moq/callbacks

Implicit Mocks

When mocking interfaces that don’t need any configuration or verification, use implicit mocks:

var logger = Mock.Of<ILogger>();

This is equivalent to:

var mock = new Mock<ILogger>();
var logger = mock.Object;

To get the underlying mock:

var mock = Mock.Get(logger);

Mocking a Type with Generic Methods

Consider this interface:

public interface IService
{
    void DoSomething<T>(T argument);
}

Use It.IsAnyType to configure the mocked method to accept any type:

mock.Setup(p => p.DoSomething(It.IsAny<It.IsAnyType>()))
    .Callback((object value) => TestContext.Progress.Writeline($"DoSomething: {value}"));

Use It.IsSubtype to constrain the incoming type parameter:

mock.Setup(p => p.DoSomething(It.IsAny<It.IsSubtype<IList<string>>>()))
    .Callback((IList<string> items) => TestContext.Progress.Writeline($"Received list of {items.Count} strings"));

mock.Setup(p => p.DoSomething(It.IsAny<It.IsSubtype<IList<int>>>()))
    .Throws<ArgumentException>();

Mocking a Type That Inherits Multiple Interfaces

Consider this class that inherits more than one interface:

public class Dependency : IDependency, IDisposable { ... }

To mock it:

var mock = new Mock<IDependency>();
var mockDisposable = mock.As<IDisposable>();

Or, to access the mock of the IDisposable interface from mock:

mock.As<IDisposable>().Setup(p => p.Dispose());