Microsoft Fakes: The solution to our .Net testing woes? (NUnit)

Did you know you can “shim” system assemblies such as DateTime, HttpWebRequest, and more! Until now, I would simply curse out loud, create wrappers around static helpers and then crawl into a corner and cry. This awesome new feature will allows us to use .NET code the way Microsoft initially intended and not be scared of isolation for testing; we should however be cautious not to abuse this feature: only use it to mock .NET code and ensure all of your own custom code is written properly in a testable manner.

Firstly, it is important that you MUST be using Visual Studio 2012 (sp2) Ultimate or Premium.

What are shims?

Shims allow you to test your code without worrying about the static, internal and unmockable helpers that you are using within your code. They do so without requiring any modification of your production code; it’s basically good, documented magic. The link below shows an example of how to stub the static DateTime.Now property.

Here is the MSDN article: http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx

One of the down-sides, is that you cannot use the re-sharper Unit-Test runner, you MUST use the built in Visual Studio test runner (which is why you would need to NUnit Test Adapter). This also means that you need to use the Visual Studio test runner on your build server; hence the two last links.

Microsoft also has had a feature called Moles which is the equivalent for Visual Studio 2010. However, it has been superseded with the Fakes library and Visual Studio 2012 will not be supporting Moles. I have seen some attempts to make them continue working in Visual Studio 2012 (http://molesvs2012.codeplex.com/) but why use an old technology which is bound to lose support now?

So if you are lucky enough to be rocking Visual Studio 2012 at work, I suggest you look into this new feature and increase your test coverage right now.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s