Currently
I’m using Moq to create a handful of mock objects; thus far everything is working nicely. Currently to ‘assign’ a delegate using Moq I’m doing
var someMock = new Mock<ISomeInterface>();
someMock.Setup(x => x.DoSomething(It.IsAny<int>())).Returns(this.DoSomething)
Where this.DoSomething is a method accepting an int parameter; fundamentally it’s the same structure as x.DoSomething on the ISomeInterface.
Question
Is it possible to simply assign a delegate, without the neeed for specifying all of its parameters, i.e. not using It.IsAny<int>()? Ideally something like this:
var someMock = new Mock<ISomeInterface>();
someMock.Setup(x => x.DoSomething).Returns(this.DoSomething)
No, that’s not possible. That’s not a “shortcoming” of Moq – C# doesn’t support it.
Some background:
Let’s assume
ISomeInterfaceis declared as follows:That would mean that the parameter of the
Setupmethod would have to be aFunc<ISomeInterface, Action<int, int>>.The problem now is that the
Setupmethod would have to be defined in a generic way, because your method could have any type of parameters:Tis the generic type from the Mock class,T1andT2are the parameters of the method.Calling this method however will result in a compiler error:
To make it work, you would need to call it like this:
or like this:
In both cases, you would have to specify the type of the parameters, just as you do it now already.
As to why you get the compiler error:
x.DoSomethingis a method group. There exists an implicit conversion toAction<int, int>.However, for this implicit conversion to be executed, the compiler needs to know the types of
T1andT2. But those types can only be inferred after the conversion took place.Those two steps depend on each other and that’s why it doesn’t work.