Unit Test class that makes use of HttpWebRequest thanks to Visual Studio fakes library
By: Ricci Gian Maria
Thanks to Visual Studio Fakes is it possible to isolate your unit test and testing difficult to test code. Today I need to test a class that issues some Web Request around the internet and Iím concerned about testing the SUT when the web response contains some specific code like 404 (Not Found) or something.
If you simply right-click the reference to system assembly in your project and Add a fakes assembly, you probably will be annoyed by the fact that when you try to create a ShimHttpWebRequest you are not able to do it. When some shim are not available, the reason is usually due to some limitation of fakes library, so types are skipped when shims and stub code are generated (during compilation).
Apart not being able to use a shim of HttpWebRequest, when you add a fakes assembly to Visual Studio test project, you are actually asking to the fakes library to create a stub and a shim for every class of that assembly, and this can be a problem because
1. Your build time increase
2. Some classes probably will not be generated due to Fakes Limitation
Solution is simple, just locate the System.Fakes files under Fakes directory of your test project, they usually contain only the name of the assembly and nothing more. This is the default and basically it means: Create a shim and a stub for every type in that assembly. You should change that file to specify only the types you are really going to use in your Unit Tests. Es.
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
<Assembly Name="System" Version="188.8.131.52"/>
This code is actually instructing the Fakes library on what class you are going to use. In the above example Iím telling that Iím not going to use any Stub and I want to use Shim for WebRequest, HttpWebRequest and HttpWebResponse. If you specify only the classes you are really going to isolate, build time will be shorter, and there is much more possibility that shims gets generated.
Remember also that when you create fake library for System assembly you actually will get two distinct fakes configuration, one for system, and the other for Mscorlib.fakes. I usually modify the mscorlib.fakes in such a way.
... to read more articles, visit http://sqa.fyicenter.com/art/