Visual Studio Shims and Fakes

Microsoft Visual Studio 2013 includes Fakes (Premium and above) to isolate existing code. This involves intercepting calls to the framework and rerouting them to Shims. These Shims are created by right clicking a reference and selecting “Add Fakes Assembly”. But sometimes a little manual override is needed to get things working.

[TestMethod]
public void Stub_environment_and_dns() {
   // arrange
   using (ShimsContext.Create()) {
      System.Fakes.ShimEnvironment.MachineNameGet = () => "hello";
      System.Net.Fakes.ShimDns.GetHostName = () => "world";

   // act
      var result = string.Format("{0} {1}",
         System.Environment.MachineName,
         System.Net.Dns.GetHostName());

   // assert
      Assert.AreEqual("hello world", result);
   }
}

To get the above code to work edit the mscorlib.fakes and System.fakes files. We need to instruct the generator to create fakes for System.Net.Dns and System.Environment.

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
   <Assembly Name="System" Version="4.0.0.0" />
   <ShimGeneration>
      <Add FullName="System.Net.Dns"/>
   </ShimGeneration>
</Fakes>
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
   <Assembly Name="mscorlib" Version="4.0.0.0"/>
   <ShimGeneration>
      <Add FullName="System.Environment"/>
   </ShimGeneration>
</Fakes>

Still the build output contains warnings:

1>mscorlib.fakes : warning : Some fakes could not be generated. For complete details, set Diagnostic attribute of the Fakes element in this file to ‘true’ and rebuild the project.
1>System.fakes : warning : Some fakes could not be generated. For complete details, set Diagnostic attribute of the Fakes element in this file to ‘true’ and rebuild the project.

This makes me reserved in using this for my projects.

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , . Bookmark the permalink.

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