The other day I was writing some unit tests on an MVC project. I needed to mock (fake) an HttpRequest object using the System.Web assembly. However, there was a strange issue in creating the fakes assembly and adding it to my Visual Studio solution. Namely, it didn’t show up.
Here’s what I found…
In your unit testing project, right-click on the System.Web assembly. Then, click on “Add Fakes Assembly”.
As expected, I could see System.Web.fakes metadata file created. But, no fakes assembly.
Additionally, if I look at my Error List in Visual Studio, I see a slew of errors. Because of these errors the assembly couldn’t be generated. Therefore, we’ll need to update the System.Web.fakes metadata file to include/exclude specific namespaces in order to create the fakes assembly.
Edit the metadata file to look like the following:
<Assembly Name="System.Web" Version="220.127.116.11"/>
With the above XML, I am instructing the fakes framework to only add stubs for the interfaces and create shims for the System.Web namespace only – not any other contained namespaces. With this modification to the metadata file, my unit test project now compiles without any issues. Unfortunately, I still don’t see the System.Web.fakes assembly referenced and I cannot use my fakes assembly in my unit tests. One more step to fix this…
Right-click on one of your application’s libraries (in my case, WebApplication2) and click on “Add Fakes Assembly”. Upon doing this, you’ll now see not only the fakes assembly to your application’s library, but also the fakes assembly for System.Web.
You can now delete the fakes assembly and associated metadata for your assembly (i.e. WebApplication2) if you’d like.