Question

I am using Microsoft Fakes framework within VS2012.

I use the following code to shim instance methods of my type.

    using (ShimsContext.Create())
    {
        ShimDateTime.NowGet = () => { return new DateTime(1949, 10, 1); };
        DateTime now = DateTime.Now;  // shim works for the static property DateTime.Now.

        Class1 dependency = new Class1();


        using (ShimsContext.Create())
        {
            ShimClass1 shim1 = new ShimClass1();
            StubClass1 stub1 = new StubClass1();
            shim1.method1 = () => { return "shim method1"; };
            shim1.IMethod1 = () => { return "shim IMethod1"; };

            String s1 = dependency.method1();// shim doesn't work for the instance method.
            String s2 = dependency.IMethod1();// shim doesn't work for the instance method.
        }

The class1 and looks like this:

public class Class1 : Interface1
{
    public String method1()
    {
        return "real method1";
    }

    //Interface 1 member
    public string IMethod1()
    {
        return "real IMethod1";
    }
}

I expect the s1 and s2 to be the shimed output, but it is still real output.

Why?

Was it helpful?

Solution

If 'method1' was static your shim would have worked. However with the current code you have not really shimmed out 'method1'. You need to either associate the instance with the shim instance

Class1 dependency = new ShimClass1() { Method1 = () => { return "Shim.Method1"; } };

or associate all instance methods with your delegate

ShimClass1.AllInstances.Method1 = (q)=> { return "Shim.Method1"; };

Also I dont see the need to have the ShimsContext.Create() done twice

If you want to use stubs to redirect IMethod1 you should be consuming the StubInterface1 instead

Class1 dependency = new StubInterface1() { Method1 = () { return ""; } };

Variations of these are available on msdn for reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top