Page 1 of 1 in the Moq category
# Wednesday, July 21, 2010
« A way to Pass data from an ASP.NET MVC V... | Main | Show Git repository status on a Windows ... »
Close up blog entry

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:

  
[TestFixture]
public class TestFixture1
{
   public interface ITest
   {
      int Func(int x, int y);
   }

   [Test]
   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 :-)

.NET | Moq | Technical
Share/Bookmark
Wednesday, July 21, 2010 11:18:25 PM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |