Fakes

I recently came across Microsoft Fakes which can help you when doing TDD to isolate the code under test. Initially I thought it was only available with Visual Studio Ultimate Edition but if you install Visual Studio Update 2 it is now available in the premium edition as well.

Fakes gives you the ability to write stubs and shims. If your code is loosely coupled and you are programming to interfaces you can use stubs to isolate your code. A stub would implement the same interface as the object you are replacing and you can program it to expect certain inputs and return certain outputs. The part of Fakes I was more interested in was shims. As I mentioned before ideally your code will use interfaces but sometimes you need to rely on third party assemblies and won’t have control over how they are written. Where this is the case a shim can help. A shim modifies your compile time code making it use the shim code instead of the specified method call.

There is lots of information here on how to use Fakes so I won’t repeat it but just to give you an idea of how easy it is to use take a look at this article. Once you have a version of Visual Studio which supports Fakes you can include the assembly you are faking in your test project. Right click on it and select the “Add Fakes Assembly” option. This will generate you a fake assembly which you can use to implement shims in your unit tests.

If you look at the example Microsoft provide you can see you need to use the shim within a Shim Context. In this case we are using a shim to replace the DateTime Now functionality and make it return a predefined date instead of the current time.