Moq – Use Setup arguments (parameters) in the Returns of a mocked function

I recommend

It can be useful when mocking a function with Moq to use parameters passed into the Setup of a mocked function in the Returns function.

I created a unit test to illustrate the basic idea:

public class TestFixture1
   public interface ITest
      int Func(int x, int y);

   public void Test()
      Mock<ITest> mockTest = new Mock<ITest>(MockBehavior.Strict);

      mockTest.Setup(x => x.Func(It.IsAny<int>(), It.IsAny<int>()))
         .Returns((int x, int y) => { return FuncData(x, y); });

      ITest test = mockTest.Object;

      Assert.AreEqual(5, test.Func(2, 3));
      Assert.AreEqual(3, test.Func(1, 2));

   private int FuncData(int x, int y)
      return x + y;

The main idea is to use a lambda expression in the Returns function that specifies the arguments that can be used in whatever way is needed.

I created a short screen cast to demo how this works:

I hope this helps! Code on :-)

Technical .NET Moq July 21, 2010

comments powered by Disqus