Create mocks
You can create mocks for interfaces and classes. For classes without a default constructor, use
BaseClass.WithConstructorParameters(…) to provide constructor arguments:
// Create a mock for an interface
IChocolateDispenser sut = Mock.Create<IChocolateDispenser>();
// Create a mock for a class
MyChocolateDispenser classMock = Mock.Create<MyChocolateDispenser>();
// For classes without a default constructor:
MyChocolateDispenserWithCtor classWithArgsMock = Mock.Create<MyChocolateDispenserWithCtor>(
BaseClass.WithConstructorParameters("Dark", 42)
);
You can specify up to eight additional interfaces that the mock also implements (beyond the first type):
// return type is a MyChocolateDispenser that also implements ILemonadeDispenser
var sut = Mock.Create<MyChocolateDispenser, ILemonadeDispenser>();
Notes:
- Only the first generic type can be a class; additional types must be interfaces.
- Sealed classes cannot be mocked and will throw a
MockException.
Customizing mock behavior
You can control the default behavior of the mock by providing a MockBehavior:
var strictMock = Mock.Create<IChocolateDispenser>(MockBehavior.Default with { ThrowWhenNotSetup = true });
// For classes with constructor parameters and custom behavior:
var classMock = Mock.Create<MyChocolateDispenser>(
BaseClass.WithConstructorParameters("Dark", 42),
new MockBehavior { ThrowWhenNotSetup = true }
);
MockBehavior options
SkipBaseClass(bool):- If
false(default), the mock will call the base class implementation and use its return values as default values, if no explicit setup is defined. - If
true, the mock will not call any base class implementations.
- If
ThrowWhenNotSetup(bool):- If
false(default), the mock will return a default value (seeDefaultValue), when no matching setup is found. - If
true, the mock will throw an exception when no matching setup is found.
- If
DefaultValue(IDefaultValueGenerator):- Customizes how default values are generated for methods/properties that are not set up.
- The default implementation provides sensible defaults for the most common use cases:
- Empty collections for collection types (e.g.,
IEnumerable<T>,List<T>, etc.) - Empty string for
string - Completed tasks for
Task,Task<T>,ValueTaskandValueTask<T> - Tuples with recursively defaulted values
nullfor other reference types
- Empty collections for collection types (e.g.,
- You can add custom default value factories for specific types using
.WithDefaultValueFor<T>():This is useful when you want mocks to return specific default values for certain types instead of the standard defaults.var behavior = MockBehavior.Default
.WithDefaultValueFor<string>(() => "default")
.WithDefaultValueFor<int>(() => 42);
var sut = Mock.Create<IChocolateDispenser>(behavior);
Initialize<T>(params Action<IMockSetup<T>>[] setups):- Automatically initialize all mocks of type T with the given setups when they are created.
- The callback can optionally receive an additional counter parameter, allowing you to differentiate between multiple
automatically created instances.
For example, when initializing
IDbConnectionmocks, you can use the counter to assign different database names or connection strings to each mock so they can be verified independently.
UseConstructorParametersFor<T>(object?[]):- Configures constructor parameters to use when creating mocks of type
T, unless explicit parameters are provided during mock creation viaBaseClass.WithConstructorParameters(…).
- Configures constructor parameters to use when creating mocks of type
Using a factory for shared behavior
Use Mock.Factory to create multiple mocks with a shared behavior:
var behavior = MockBehavior.Default with { ThrowWhenNotSetup = true };
var factory = new Mock.Factory(behavior);
var sut1 = factory.Create<IChocolateDispenser>();
var sut2 = factory.Create<ILemonadeDispenser>();
Using a factory allows you to create multiple mocks with identical, centrally configured behavior. This is especially useful when you need consistent mock setups across multiple tests or for different types.
Wrapping existing instances
You can wrap an existing instance with mock tracking using Mock.Wrap<T>(). This allows you to track interactions with
a real object:
var realDispenser = new MyChocolateDispenser();
var wrappedDispenser = Mock.Wrap<IChocolateDispenser>(realDispenser);
// Calls are forwarded to the real instance
wrappedDispenser.Dispense("Dark", 5);
// But you can still verify interactions
wrappedDispenser.VerifyMock.Invoked.Dispense(It.Is("Dark"), It.Is(5)).Once();
Notes:
- Only interface types can be wrapped with
Mock.Wrap<T>(). - All calls are forwarded to the wrapped instance.
- You can still set up custom behavior that overrides the wrapped instance's behavior.
- You cannot override protected members of the wrapped instance.
- Verification works the same as with regular mocks.