BT

Deep Dive With Microsoft Fakes – Shims

by Roopesh Shenoy on May 22, 2012 |

Shims are a part of the Microsoft Fakes framework that allow Method interception as a part of testing – including framework methods. This allows for lesser intrusive unit testing, shows Rich Czyzewski in his article, “Noninvasive Unit Testing in ASP.NET MVC4 – A Microsoft Fakes Deep Dive”.

What exactly is non-invasive testing? Rich provides a simple example where a call to FormsAuthentication.SignOut() currently needs to be wrapped in a separate class so that the calling object can be unit tested, since FormsAuthentication depends on HttpContext which is not initialized when running the tests. This is intrusive, because it mandates a change in design just for the sake of testability.

Shims on the other hand can allow call to FormsAuthentication.SignOut() to be intercepted and instead call our own implementation – this allows us avoid having wrapping classes just for the sake of testability and makes testing lesser intrusive. 

For those who are new to the Microsoft Fakes Framework, Shim Types can be used to intercept and replace all kinds of method calls -

  • Static methods
  • Instance methods (for all instances or for a particular instance)
  • Normal and Static Constructors

Shims can also be bound to interfaces instead faking classes.

The Fakes Framework can be used with any Unit Testing framework, including NUnit. Rich also has a good comparison between the Moles technology introduced with VS 2010 and Fakes introduced in VS 11 which have very similar features.

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Mandating Design changes by Peter Gfader

>>since FormsAuthentication depends on HttpContext which is not initialized when running the tests.
>>This is intrusive, because it mandates a change in design just for the sake of testability.

This would clearly mandate a design change...
but in the framework: Make FormsAuthentication independent from HttpContext.
Or abstract the static class FormsAuthentication away...

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

1 Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT