Mockolate 0.46.0

dotnet add package Mockolate --version 0.46.0
                    
NuGet\Install-Package Mockolate -Version 0.46.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Mockolate" Version="0.46.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Mockolate" Version="0.46.0" />
                    
Directory.Packages.props
<PackageReference Include="Mockolate" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Mockolate --version 0.46.0
                    
#r "nuget: Mockolate, 0.46.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Mockolate@0.46.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Mockolate&version=0.46.0
                    
Install as a Cake Addin
#tool nuget:?package=Mockolate&version=0.46.0
                    
Install as a Cake Tool

Mockolate

Changelog Nuget Coverage

Mockolate logo

Mockolate is a modern, strongly-typed mocking library for .NET, powered by source generators. It enables fast, compile-time validated mocks for interfaces and classes, supporting .NET Standard 2.0, .NET 8, .NET 10, and .NET Framework 4.8.

  • Source generator-based: No runtime proxy generation, fast and reliable.
  • Strongly-typed: Setup and verify mocks with full IntelliSense and compile-time safety.
  • AOT compatible: Works with NativeAOT and trimming.

Getting Started

  1. Install the Mockolate nuget package

    dotnet add package Mockolate
    
  2. Create and use the mock

    using Mockolate;
    
    public delegate void ChocolateDispensedDelegate(string type, int amount);
    public interface IChocolateDispenser
    {
        int this[string type] { get; set; }
        int TotalDispensed { get; set; }
        bool Dispense(string type, int amount);
        event ChocolateDispensedDelegate ChocolateDispensed;
    }
    
    // Create a mock for IChocolateDispenser
    var sut = Mock.Create<IChocolateDispenser>();
    
    // Setup: Initial stock of 10 for Dark chocolate
    sut.SetupMock.Indexer(It.Is("Dark")).InitializeWith(10);
    // Setup: Dispense decreases Dark chocolate if enough, returns true/false
    sut.SetupMock.Method.Dispense(It.Is("Dark"), It.IsAny<int>())
        .Returns((type, amount) =>
        {
            var current = sut[type];
            if (current >= amount)
            {
                sut[type] = current - amount;
                sut.RaiseOnMock.ChocolateDispensed(type, amount);
                return true;
            }
            return false;
        });
    
    // Track dispensed amount via event
    int dispensedAmount = 0;
    sut.ChocolateDispensed += (type, amount)
    {
        dispensedAmount += amount;
    }
    
    // Act: Try to dispense chocolates
    bool gotChoc1 = sut.Dispense("Dark", 4); // true
    bool gotChoc2 = sut.Dispense("Dark", 5); // true
    bool gotChoc3 = sut.Dispense("Dark", 6); // false
    
    // Verify: Check interactions
    sut.VerifyMock.Invoked.Dispense(It.Is("Dark"), It.IsAny<int>()).Exactly(3);
    
    // Output: "Dispensed amount: 9. Got chocolate? True, True, False"
    Console.WriteLine($"Dispensed amount: {dispensedAmount}. Got chocolate? {gotChoc1}, {gotChoc2}, {gotChoc3}");
    

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
var sut = Mock.Create<IChocolateDispenser>();

// Create a mock for a class
var classMock = Mock.Create<MyChocolateDispenser>();

// For classes without a default constructor:
var classWithArgsMock = Mock.Create<MyChocolateDispenserWithCtor>(
    BaseClass.WithConstructorParameters("Dark", 42)
);

// Specify up to 8 additional interfaces for the mock:
var sut2 = 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>(new MockBehavior { 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
  • ThrowWhenNotSetup (bool):
    • If false (default), the mock will return a default value (see DefaultValue).
    • If true, the mock will throw an exception when a method or property is called without a setup.
  • CallBaseClass (bool):
    • If false (default), the mock will not call any base class implementations.
    • If true, the mock will call the base class implementation and use its return values as default values, if no explicit setup is defined.
  • Initialize<T>(params Action<IMockSetup<T>>[] setups):
    • Automatically initialize all mocks of type T with the given setups when they are created.
  • 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>, ValueTask and ValueTask<T>
      • Tuples with recursively defaulted values
      • null for other reference types

Using a factory for shared behavior

Use Mock.Factory to create multiple mocks with a shared behavior:

var behavior = new MockBehavior { 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.

Setup

Set up return values or behaviors for methods, properties, and indexers on your mock. Control how the mock responds to calls in your tests.

Method Setup

Use mock.SetupMock.Method.MethodName(…) to set up methods. You can specify argument matchers for each parameter.

// Setup Dispense to decrease stock and raise event
sut.SetupMock.Method.Dispense(It.Is("Dark"), It.IsAny<int>())
    .Returns((type, amount) =>
    {
        var current = sut[type];
        if (current >= amount)
        {
            sut[type] = current - amount;
            sut.RaiseOnMock.ChocolateDispensed(type, amount);
            return true;
        }
        return false;
    });

// Setup method with callback
sut.SetupMock.Method.Dispense(It.Is("White"), It.IsAny<int>())
    .Do((type, amount) => Console.WriteLine($"Dispensed {amount} {type} chocolate."));

// Setup method to throw
sut.SetupMock.Method.Dispense(It.Is("Green"), It.IsAny<int>())
    .Throws<InvalidChocolateException>();
  • Use .Do(…) to run code when the method is called. Supports parameterless or parameter callbacks.
  • Use .Returns(…) to specify the value to return. You can provide a direct value, a callback, or a callback with parameters.
  • Use .Throws(…) to specify an exception to throw. Supports direct exceptions, exception factories, or factories with parameters.
  • Use .Returns(…) and .Throws(…) repeatedly to define a sequence of return values or exceptions (cycled on each call).
  • Use .CallingBaseClass(…) to override the base class behavior for a specific method (only for class mocks).
  • When you specify overlapping setups, the most recently defined setup takes precedence.

Async Methods

For Task<T> or ValueTask<T> methods, use .ReturnsAsync(…):

sut.SetupMock.Method.DispenseAsync(It.IsAny<string>(), It.IsAny<int>())
    .ReturnsAsync(true);
Parameter Matching

Mockolate provides flexible parameter matching for method setups and verifications:

  • It.IsAny<T>(): Matches any value of type T.
  • It.Is<T>(value): Matches a specific value. With .Using(IEqualityComparer<T>), you can provide a custom equality comparer.
  • It.IsOneOf<T>(params T[] values): Matches any of the given values. With .Using(IEqualityComparer<T>), you can provide a custom equality comparer.
  • It.IsNull<T>(): Matches null.
  • It.IsTrue()/It.IsFalse(): Matches boolean true/false.
  • It.IsInRange(min, max): Matches a number within the given range. You can append .Exclusive() to exclude the minimum and maximum value.
  • It.IsOut<T>(…)/It.IsAnyOut<T>(…): Matches and sets out parameters, supports value setting and predicates.
  • It.IsRef<T>(…)/It.IsAnyRef<T>(…): Matches and sets ref parameters, supports value setting and predicates.
  • It.Matches<string>(pattern): Matches strings using wildcard patterns (* and ?). With .AsRegex(), you can use regular expressions instead.
  • It.Satisfies<T>(predicate): Matches values based on a predicate.
Parameter Interaction

With Do, you can register a callback for individual parameters of a method setup. This allows you to implement side effects or checks directly when the method or indexer is called. With .Monitor(out monitor), you can track the actual values passed during test execution and analyze them afterwards.

Example: Do for method parameter

int lastAmount = 0;
sut.SetupMock.Method.Dispense(It.Is("Dark"), It.IsAny<int>().Do(amount => lastAmount = amount));
sut.Dispense("Dark", 42);
// lastAmount == 42

Example: Monitor for method parameter

Mockolate.ParameterMonitor<int> monitor;
sut.SetupMock.Method.Dispense(It.Is("Dark"), It.IsAny<int>().Monitor(out monitor));
sut.Dispense("Dark", 5);
sut.Dispense("Dark", 7);
// monitor.Values == [5, 7]

Property Setup

Set up property getters and setters to control or verify property access on your mocks.

Initialization

You can initialize properties so they work like normal properties (setter changes the value, getter returns the last set value):

sut.SetupMock.Property.TotalDispensed.InitializeWith(42);

Returns / Throws

Alternatively, set up properties with Returns and Throws (supports sequences):

sut.SetupMock.Property.TotalDispensed
    .Returns(1)
    .Returns(2)
    .Throws(new Exception("Error"))
    .Returns(4);

Callbacks

Register callbacks on the setter or getter:

sut.SetupMock.Property.TotalDispensed.OnGet(() => Console.WriteLine("TotalDispensed was read!"));
sut.SetupMock.Property.TotalDispensed.OnSet((oldValue, newValue) => Console.WriteLine($"Changed from {oldValue} to {newValue}!") );

Indexer Setup

Set up indexers with argument matchers. Supports initialization, returns/throws sequences, and callbacks.

sut.SetupMock.Indexer(It.IsAny<string>())
    .InitializeWith(type => 20)
    .OnGet(type => Console.WriteLine($"Stock for {type} was read"));

sut.SetupMock.Indexer(It.Is("Dark"))
    .InitializeWith(10)
    .OnSet((value, type) => Console.WriteLine($"Set [{type}] to {value}"));
  • .InitializeWith(…) can take a value or a callback with parameters.
  • .Returns(…) and .Throws(…) support direct values, callbacks, and callbacks with parameters and/or the current value.
  • .OnGet(…) and .OnSet(…) support callbacks with or without parameters.
  • .Returns(…) and .Throws(…) can be chained to define a sequence of behaviors, which are cycled through on each call.
  • Use .CallingBaseClass(…) to override the base class behavior for a specific indexer (only for class mocks).
  • When you specify overlapping setups, the most recently defined setup takes precedence.

Note: You can use the same parameter matching and interaction options as for methods.

Mock events

Easily raise events on your mock to test event handlers in your code.

Raise

Use the strongly-typed Raise property on your mock to trigger events declared on the mocked interface or class. The method signature matches the event delegate.

// Arrange: subscribe a handler to the event
sut.ChocolateDispensed += (type, amount) => { /* handler code */ };

// Act: raise the event
sut.RaiseOnMock.ChocolateDispensed("Dark", 5);
  • Use the Raise property to trigger events declared on the mocked interface or class.
  • Only currently subscribed handlers will be invoked.
  • Simulate notifications and test event-driven logic in your code.

Example:

int dispensedAmount = 0;
sut.ChocolateDispensed += (type, amount) => dispensedAmount += amount;

sut.RaiseOnMock.ChocolateDispensed("Dark", 3);
sut.RaiseOnMock.ChocolateDispensed("Milk", 2);

// dispensedAmount == 5

You can subscribe and unsubscribe handlers as needed. Only handlers subscribed at the time of raising the event will be called.

Verify interactions

You can verify that methods, properties, indexers, or events were called or accessed with specific arguments and how many times, using the Verify API:

Supported call count verifications in the Mockolate.VerifyMock namespace:

  • .Never()
  • .Once()
  • .Twice()
  • .Exactly(n)
  • .AtLeastOnce()
  • .AtLeastTwice()
  • .AtLeast(n)
  • .AtMostOnce()
  • .AtMostTwice()
  • .AtMost(n)

Methods

You can verify that methods were invoked with specific arguments and how many times:

// Verify that Dispense("Dark", 5) was invoked at least once
sut.VerifyMock.Invoked.Dispense(It.Is("Dark"), It.Is(5)).AtLeastOnce();

// Verify that Dispense was never invoked with "White" and any amount
sut.VerifyMock.Invoked.Dispense(It.Is("White"), It.IsAny<int>()).Never();

// Verify that Dispense was invoked exactly twice with any type and any amount
sut.VerifyMock.Invoked.Dispense(Match.AnyParameters()()).Exactly(2);
Argument Matchers

You can use argument matchers from the With class to verify calls with flexible conditions:

  • It.IsAny<T>(): Matches any value of type T.
  • It.Is<T>(value): Matches a specific value. With .Using(IEqualityComparer<T>), you can provide a custom equality comparer.
  • It.IsOneOf<T>(params T[] values): Matches any of the given values. With .Using(IEqualityComparer<T>), you can provide a custom equality comparer.
  • It.IsNull<T>(): Matches null.
  • It.IsTrue()/It.IsFalse(): Matches boolean true/false.
  • It.IsInRange(min, max): Matches a number within the given range. You can append .Exclusive() to exclude the minimum and maximum value.
  • It.IsOut<T>(): Matches any out parameter of type T
  • It.IsRef<T>(): Matches any ref parameter of type T
  • It.Matches<string>(pattern): Matches strings using wildcard patterns (* and ?). With .AsRegex(), you can use regular expressions instead.
  • It.Satisfies<T>(predicate): Matches values based on a predicate.

Example:

sut.VerifyMock.Invoked.Dispense(It.Is<string>(t => t.StartsWith("D")), It.IsAny<int>()).Once();
sut.VerifyMock.Invoked.Dispense(It.Is("Milk"), It.IsAny<int>()).AtLeastOnce();

Properties

You can verify access to property getter and setter:

// Verify that the property 'TotalDispensed' was read at least once
sut.VerifyMock.Got.TotalDispensed().AtLeastOnce();

// Verify that the property 'TotalDispensed' was set to 42 exactly once
sut.VerifyMock.Set.TotalDispensed(It.Is(42)).Once();

Note:
The setter value also supports argument matchers.

Indexers

You can verify access to indexer getter and setter:

// Verify that the indexer was read with key "Dark" exactly once
sut.VerifyMock.GotIndexer(It.Is("Dark")).Once();

// Verify that the indexer was set with key "Milk" to value 7 at least once
sut.VerifyMock.SetIndexer(It.Is("Milk"), 7).AtLeastOnce();

Note:
The keys and value also supports argument matchers.

Events

You can verify event subscriptions and unsubscriptions:

// Verify that the event 'ChocolateDispensed' was subscribed to at least once
sut.VerifyMock.SubscribedTo.ChocolateDispensed().AtLeastOnce();

// Verify that the event 'ChocolateDispensed' was unsubscribed from exactly once
sut.VerifyMock.UnsubscribedFrom.ChocolateDispensed().Once();

Call Ordering

Use Then to verify that calls occurred in a specific order:

sut.VerifyMock.Invoked.Dispense(It.Is("Dark"), It.Is(2)).Then(
    m => m.Invoked.Dispense(It.Is("Dark"), It.Is(3))
);

You can chain multiple calls for strict order verification:

sut.VerifyMock.Invoked.Dispense(It.Is("Dark"), It.Is(1)).Then(
    m => m.Invoked.Dispense(It.Is("Milk"), It.Is(2)),
    m => m.Invoked.Dispense(It.Is("White"), It.Is(3)));

If the order is incorrect or a call is missing, a MockVerificationException will be thrown with a descriptive message.

Check for unexpected interactions

  1. ThatAllInteractionsAreVerified:
    You can check if all interactions with the mock have been verified using ThatAllInteractionsAreVerified:

    // Returns true if all interactions have been verified before
    bool allVerified = sut.VerifyMock.ThatAllInteractionsAreVerified();
    

    This is useful for ensuring that your test covers all interactions and that no unexpected calls were made. If any interaction was not verified, this method returns false.

  2. ThatAllSetupsAreUsed:
    You can check if all registered setups on the mock have been used using ThatAllSetupsAreUsed:

    // Returns true if all setups have been used
    bool allUsed = sut.VerifyMock.ThatAllSetupsAreUsed();
    

    This is useful for ensuring that your test setup and test execution match. If any setup was not used, this method returns false.

Analyzers

Mockolate ships with some Roslyn analyzers to help you adopt best practices and catch issues early, at compile time. All rules provide actionable messages and link to identifiers for easy filtering.

Mockolate0001

Verify methods only return a VerificationResult and do not directly throw. You have to specify how often you expect the call to happen, e.g. .AtLeastOnce(), .Exactly(n), etc. or use the verification result in any other way.

Example:

var sut = Mock.Create<IChocolateDispenser>();
sut.Dispense("Dark", 1);
// Analyzer Mockolate0001: Add a count assertion like .AtLeastOnce() or use the result.
sut.VerifyMock.Invoked.Dispense(It.Is("Dark"), It.IsAny<int>());

The included code fixer suggests to add the .AtLeastOnce() count assertion:

sut.VerifyMock.Invoked.Dispense(It.Is("Dark"), It.IsAny<int>()).AtLeastOnce();

Mockolate0002

Mock arguments must be mockable (interfaces or supported classes). This rule will prevent you from using unsupported types (e.g. sealed classes) when using Mock.Create<T>().

Mockolate0003

Wrap type arguments must be interfaces. This rule will prevent you from using non-interface types as the type parameter when using Mock.Wrap<T>(T instance).

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.
  • net10.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Mockolate:

Package Downloads
aweXpect.Mockolate

Expectations to verify interactions with mocks from Mockolate.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.46.0 151 12/23/2025
0.45.0 166 12/13/2025
0.44.0 107 12/13/2025
0.43.0 406 12/11/2025
0.42.0 414 12/8/2025
0.41.0 255 12/5/2025
0.40.0 251 12/4/2025
0.39.0 183 12/4/2025
0.38.1 624 12/1/2025
0.38.0 253 11/30/2025
0.37.0 177 11/26/2025
0.36.0 329 11/24/2025
0.35.1 202 11/24/2025
0.35.0 196 11/24/2025
0.34.0 153 11/23/2025
0.33.0 156 11/22/2025
0.32.1 391 11/20/2025
0.32.0 385 11/20/2025
0.31.2 388 11/19/2025
0.31.1 385 11/19/2025
0.31.0 387 11/19/2025
0.30.0 219 11/16/2025
0.28.0 131 11/8/2025
0.27.0 184 11/5/2025
0.26.0 184 11/4/2025
0.25.0 190 11/2/2025
0.24.0 119 11/1/2025
0.23.0 115 11/1/2025
0.22.0 160 10/26/2025
0.21.0 160 10/26/2025
0.20.0 140 10/26/2025
0.19.0 136 10/25/2025
0.18.0 99 10/25/2025
0.17.0 96 10/25/2025
0.16.0 99 10/25/2025
0.15.0 96 10/25/2025
0.14.0 111 10/24/2025
0.13.0 119 10/24/2025
0.12.0 171 10/20/2025
0.11.0 109 10/18/2025
0.10.2 168 10/15/2025
0.10.1 167 10/13/2025
0.10.0 457 10/12/2025
0.9.1 216 10/12/2025
0.9.0 170 10/12/2025
0.8.0 109 10/11/2025
0.7.0 173 10/10/2025
0.6.0 164 10/8/2025
0.5.4 368 10/8/2025
0.5.3 168 10/8/2025
0.5.2 163 10/7/2025
0.5.1 168 10/7/2025
0.5.0 165 10/7/2025
0.4.0 164 10/7/2025
0.3.0 163 10/5/2025
0.2.0 164 10/5/2025
0.1.0 102 10/4/2025