Skip to content

A modern, strongly-typed mocking library for .NET, powered by source generators.

License

Notifications You must be signed in to change notification settings

aweXpect/Mockolate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Mockolate

Mockolate logo

Nuget Build Quality Gate Status Coverage Mutation testing badge

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).

About

A modern, strongly-typed mocking library for .NET, powered by source generators.

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Contributors 3

  •  
  •  
  •  

Languages