How to setup a Moq Callback for an `in` parameter modifier?

Viewed 397

How do you setup a Moq setup Callback for a method with an in parameter modifier?

Say you have this:

public interface ITester
{
   bool IsGood(in int value);
}

This doesn't work:

var mock = new Mock<ITester>();
mock.Setup(m => m.IsGood(It.IsAny<int>()))
    .Callback<int>(v => { /* whatever */ });  // ==> runtime error

mock.Object.IsGood(42);

You get the following exception:

System.ArgumentException : Invalid callback. Setup on method with parameters (in int) cannot invoke callback with parameters (int).

What's the correct way (apart from removing the in modifier altogether ;) )?

1 Answers

One possible solution is to define the delegate with the similar signature(match input arguments) and use it in the callback + use It.Ref<int>.IsAny in the setup:

public delegate void MyDelegate(in int value);
var d = new MyDelegate((in int a) => { Console.WriteLine($"Number {a}"); });

var mock = new Mock<ITester>();
mock.Setup(m => m.IsGood(It.Ref<int>.IsAny)).Callback(d);

mock.Object.IsGood(42); //Number 42
Related