Fakes Tutorial 1: Introduction to Microsoft Fakes

There has been a lots of buzz going around that there is no moles for VS 2012 and now we have to use Microsoft’s OWN unit testing framework.

So to clear that:

  1. MOLES WAS from Microsoft Only.
  2. Fakes is nothing but a differently packaged Moles J. At least from functionality perspective.
  3. You are welcome to use any other Unit testing framework if it fulfills your need and a compatible version is out there for VS 2012.

Now to begin with fakes

What is Fakes?

Fakes is isolation framework for replacing the part of code, which you don’t have control over (like webservices). Using fakes you can write your unit test and make your code believe that the values of uncontrolled part of code are coming from original source only.

Where to use it?

Let’s say we have a web service that counts the no. of rows in a database and send an Integer value to you. Depending on the integer value you show Less for value < 100, Average for value >=100 && value <1000 and More for value >=1000.

Now you can’t predict the value you will get after the service call for a particular condition as values in database constantly change.

In given scenario you will isolate that webservice, Mock it and make your code believe that the value its getting is from original service itself. Depending on Integer value you are giving while mocking you already know the output and you can Assert your unit test case against that.


Above example was one of the scenarios where you can use fakes, there can be many more scenarios like isolating your own code that you have written etc…


Some Fakes terms.

There are two different type of fakes that you can generate.

  1. Stubs: A stub is generally used to fake the code which is designed in a way that classes are inherited from interfaces.
  2. Shims: Shims are used to point your code at runtime to a method provided in test. So, shims can be used to modify behavior of assemblies.


What to use?

An excerpt from MSDN to explain all that’s there to know:

[quote]As a general guide, use stubs for calls within your Visual Studio solution, and shims for calls to other referenced assemblies. This is because within your own solution it is good practice to decouple the components by defining interfaces in the way that stubbing requires. But external assemblies such as System.dll typically are not provided with separate interface definitions, so you must use shims instead.[/quote]

Leave a Reply

Your email address will not be published. Required fields are marked *