Question

I'm using MS Fakes.

Give the following class:

public class Person
{
    public void SaveQuotes()
    {
        DoSomething();
    }

    private void DoSomething()
    {
        Console.WriteLine("Original DoSomething called.");
    }
}

and this test:

[TestMethod]
public void TestMethod1()
{
    using (ShimsContext.Create())
    {
        var sut = new ShimPerson();

        sut.DoSomething = () => { Console.WriteLine("Called from test"); };

        sut.Instance.SaveQuotes();
    }
}

When I run the test, the sut.Instance.SaveQuotes() method is basically skipped over, since that method has been shimmed. What I want is to execute the original SaveQuotes() method. So I tried this:

[TestMethod]
public void TestMethod1()
{
    using (ShimsContext.Create())
    {
        var sut = new ShimPerson();

        sut.DoSomething = () => { Console.WriteLine("Called from test"); };
        sut.SaveQuotes = () => { ShimsContext.ExecuteWithoutShims(() => sut.Instance.SaveQuotes()); };

        sut.Instance.SaveQuotes();
    }
}

When I run the test now, it does execute the original SaveQuotes(), but as a side-effect it also runs the original DoSomething() method too.

How can I run the original SaveQuotes() but the faked DoSomething(). TypeMock does this will the .CallOriginal option when setting up fakes, but I cannot see how to do the same in MS Fakes.

Était-ce utile?

La solution

OK, I got it now.

I had to change the ShimBehaviors.InstanceBeahviour property like so:

[TestMethod]
public void TestMethod1()
{
    using (ShimsContext.Create())
    {
        var sutShim = new ShimPerson();

        sutShim.DoSomething = () => { Console.WriteLine("Called from test"); };

        sutShim.InstanceBehavior = ShimBehaviors.Fallthrough;

        sutShim.Instance.SaveQuotes();
    }
}

This tells Fakes to call the original SaveQuotes() method, whilst still using the faked DoSomething() method. I found this to be a good reference:

http://www.codewrecks.com/blog/index.php/2012/05/10/shim-and-instancebehavior-fallthrough-to-isolate-part-of-the-sut/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top