fredag den 26. oktober 2018

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

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.

mandag den 22. oktober 2018

Delete all bin+obj folders using powershell

Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }