.Net: The Nasty unable to cast Object type X to X

Today I spent many hours troubleshooting the unable to cast Object type X to X . As I said in the previous blog entry, I am starting an asp.net mvc project because I want to TDD this project. So I finished translating the existing project from web forms to asp.net mvc, and now the only thing I have to confirm is that the unit test that I adapted for testing file uploads pass. (By the way, the wonderful page is found here: http://csainty.blogspot.com/2009/01/aspnet-mvc-unit-test-file-upload-wit...)

And it won't work.

I repeated the steps on how to create the mocks and how to test the entry, and it doesn't work. It give me this weird error

unable to cast Object type System.Web.Mvc.Content to System.Web.Mvc.Content

I rubbed my eyes a few times. It looks to me that it is the same. So I try it again. Same result. I recreated, step by step, the test. Same result. I researched a possible bug in NUnit. Nothing. Just in case, I repeated the test using Microsoft's test framework. Same error.

I research the specific bug connecting it to mvc. Nothing relevant. I try just the bug. This time I got a page that said that this error could be triggered by having some repeated URI references. This is potentially possible, so I decide to repeat the experiment in a new project. This time, it works using visual studio's framework. I try it again using Nunit, and it fails. I start to suspect that it is Nunit or that there is something in visual studio's framework that can make it pass. I try a third project, and this time visual studio's frameworks fails too.

So I research this error again. This time, I got this excellent link:
http://www.hanselman.com/blog/FusionLoaderContextsUnableToCastObjectOfTy...

Where Scott Hanselman explains how this error can happen from using two different DLLs. Let me quote(quote()) here:

Suzanne Cook puts it best, emphasis mine:

For example, path matters when determining whether a type is castable to another type. Even if the assemblies containing the types are identical, if they're loaded from different paths, they're considered different assemblies and therefore their types are different. This is one reason why using contexts other than the Load context is risky. You can get into situations where the same assembly is loaded multiple times in the same appdomain (once in the Load context, once in the LoadFrom context, and even several times in neither context), and their corresponding types won't be castable.

So I checked in my project, and yes, this was the problem. Those test passed right away.