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.

1 comment:

  1. At last a useful piece of information on that TargetParameterCountException. Thanks, I've been pulling my last hairs out over the last couple of hours wondering why my Returns was throwing that error. Your snippit finally gave me the answer. The Returns<> must match the parametrs, not the return signature. My method took two parameters and I'd only defined one in the Returns<>. Many thanks