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 :-)
Next entry: Show Git branch and status on a Windows PowerShell prompt
Previous Entry: A way to Pass data from an ASP.NET MVC View to the Master Page
Latest entries:
Create absolute URLs using ASP.NET MVC
Comments
My Links
Tags
Follow me
About
Powered by FoxBlog
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2011, Nathan Fox
Exactly what I needed! Thanks!
Nick - October 20, 2011