Search code examples
c#microsoft-fakes

MS Fakes: Shims with given input


Suppose that I have a method

public void SomeFunction (int a) 
{
    return AnotherFunction (a + 1);
}

Is there a way to shim AnotherFunction with specific parameters? I am thinking of something like:

using (ShimContext.Create())
{
    ShimMyClass.AnotherFunctionInt = (3) => 34; // return 34 if the given value is 3
    ShimMyClass.AnotherFunctionInt = (4) => 44; // return 44 if the given value is 4
    ShimMyClass.AnotherFunctionInt = (a) => 22; // default value
}

Solution

  • Just add code to your override instead of returning a hardcoded value. Something like

        [TestMethod]
        public void SimpleTest()
        {
            TestUnitTestClass tutClass = new TestUnitTestClass();
            using (ShimsContext.Create())
            {
                ShimTestUnitTestClass shimClass = new ShimTestUnitTestClass(tutClass);
                shimClass.AnotherFunctionInt32 = (val) =>
                {
                    if (val == 3)
                        return 34;
    
                    if (val == 4)
                        return 44;
    
                    return 22;
                };
    
                int curInt = tutClass.AnotherFunction(3);
                Console.WriteLine(curInt);
            }
        }