Sunday, 14 June 2009

Returning Method Input Parameters as the result with Moq

Today I discovered how I can return the input on a Moq Mock object as the output. Let’s imagine we have an abstract class called (oddly) EchoInput:

public abstract class EchoInput


public abstract string SayIt(string input);


We wish to create a Mock object for this abstract class that returns the value of the input as the return value for the method SayIt. To do that we simply use an overload of the Moq Return’s method that allows us to specify a Func<> delegate that simply matches the signature of the method:

var testDouble = new Mock<EchoInput>();

testDouble.Setup(mock => (mock.SayIt(Moq.It.IsAny<string>()))).Returns((string input) => input);

If you don’t match up the parameters in the call to return you will simply get a “System.Reflection.TargetParameterCountException” at runtime. This would happen if you used the example below (deliberately incorrect code):

testDouble.Setup(mock => (mock.SayIt(Moq.It.IsAny<string>())))

.Returns((string input, int x) => input);

It is worth noting that the number of parameters need to match the method’s signature. It doesn’t matter what you call the parameters but for readability it is worth giving them the same names as the original parameters.