Matthew Cox Team : Web Development Tags : Technology Web Development

Getting started with Microsoft Fakes

Matthew Cox Team : Web Development Tags : Technology Web Development

When inheriting a legacy project, if it’s well-structured it’s fairly simple to isolate and test the components and begin working, but what do you do when that’s not the case? Take the following method for example:

public static class FooFactory
{
    public static Foo GetFoo()
    {
        return new Foo()
        {
            TimeStamp = DateTime.Now
        };
    }
}

 

With an example as trivial as this you could easily refactor this method to make it testable, but refactoring without unit tests always runs the risk of introducing a regression. So how do you test this method without refactoring? This is where Microsoft Fakes come in.

Microsoft Fakes began as a Microsoft Research project called The Moles Framework. With the release of Visual Studio 2012 The Moles Framework graduated from a research project to a fully-fledged feature of Visual Studio. Microsoft Fakes basically allows you to either stub, create a new object from an interface at runtime, or shim, replace existing code with your own at runtime, anything you choose.

So how do we get started? With this example I’m only looking to shim the DateTime.Now call. So the first thing I want to do is create my Fakes assembly. To do this I right click on my System reference within my unit test project and click “Add Fakes Assembly”

This will cause Visual Studio to generate two new references mscorlib.4.0.0.0.Fakes and System.4.0.0.0.Fakes for the mscorelib.dll and the System.dll respectively.

Within each namespace that we have faked there will be a new namespace called Fakes, so since we are looking to shim System.DateTime we are looking for System.Fakes.ShimDateTime. The method we are looking for is NowGet, notice how Microsoft Fakes has created separate methods for the get and set of a property allowing you to shim each individually.

For this example we’ll just have DateTime.Now return 1/1/2000, and we do this like so:

System.Fakes.ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);

That’s really all there is to it. We just need to create a ShimsContext so that the call to DateTime.Now will get intercepted at runtime and we can test our FooFactory just as easily as if it had been written correctly in the first place.

[TestMethod]
public void GetFooTest()
{
    using (ShimsContext.Create())
    {
        System.Fakes.ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);
 
        var foo = FooFactory.GetFoo();
 
        var expected = new DateTime(2000, 1, 1);
        Assert.AreEqual(expected, foo.TimeStamp);
    }
}