I want a moq property that has an index, and I want to be able to use index values โโin a callback, just as you can use method arguments in a callback for moq'd methods. Probably the easiest way to demonstrate with an example:
public interface IToMoq { int Add(int x, int y); int this[int x] { get; set; } } Action<int, int> DoSet = (int x, int y) => { Console.WriteLine("setting this[{0}] = {1}", x, y); throw new Exception("Do I ever get called?"); }; var mock = new Mock<IToMoq>(MockBehavior.Strict); //This works perfectly mock.Setup(m => m.Add(It.IsAny<int>(), It.IsAny<int>())) .Returns<int, int>((a, b) => a + b);
Edit: To clarify, I want the callback / return method for get be Func<int,int> , and the callback / return method for set be Action<int,int> . Trying to suggest Mike, you can do this for set , but with one major limitation:
mock.SetupSet(m => m[23] = It.IsAny<int>()) .Callback(DoSet).Verifiable();
The DoSet indeed called with the values (23,<any>) . Unfortunately, using It.IsAny<int>() instead of 23 seems to behave like 0 , not <any> .
Also, I could not find a way to call SetupGet with Returns , where Returns accepts Func<int,int> , which even compiles.
Can Moq be used for this?
Motivation: I'm just playing with Moq, trying to use it to provide a free API to do the interception. That is, taking into account the I interface and the X I instance, automatically create a Mock<I> proxy with the default behavior of X
It would probably be wiser to work directly with Castle DP, but I like the syntax of the Moq expression tree.